Jo D. Jo D. - 1 year ago 38
C Question

CUnit - 'Mocking' libc functions

I'm using CUnit for my project unit testing.
I need to test whether I call libc functions with the right parameters & whether I treat their return values the right way.
for example: if I call the bind(...) function - I would like to check which af param I pass & assert if this is the wrong one, and also I would like to emulate it's return value & assert if I check it the right way.

For these purposes I would expect the CUnit environment to have a built-in mechanism to let me call a 'mocked' bind() function while testing and a real bind() function when running the code - but I can't find anything like this.

Can you please tell me if I'm missing something in CUnit, or maybe suggest a way to implement this.


Answer Source

Unfortunately, you can't mock functions in C with CUnit.

But you can implement your own mock functions by using and abusing of defines : Assuming you define UNITTEST when compiling for tests, you can in the tested file (or in a include) define something like this :

    #define bind mock_bind

In a mock_helper.c file that you will compile in test mode :

static int mock_bind_return;    // maybe a more complete struct would be usefull here
static int mock_bind_sockfd;

int mock_bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen)
    CU_ASSERT_EQUAL(sockfd, mock_bind_sockfd);
    return mock_bind_return;

Then, in your test file :

extern int mock_bind_return;
extern int mock_bind_sockfd;

void test_function_with_bind(void)

   mock_bind_return = 0;
   mock_bind_sockfd = 5;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download