Most system / library function are [weak symbols](
[To see links please register here]
). That means you can create your own implementation of them that will override the existing versions. You can then use these functions when unit testing.
Suppose you want to test the following function:
src.c:
int get_socket()
{
int s;
s = socket(AF_INET, SOCK_DGRAM, 0);
if (s == -1) {
perror("socket failed");
} else {
printf("socket success\n");
close(s);
}
return s;
}
You would then create the mock function (and any controlling variables) in a separate source file:
mock_socket.c:
int sock_rval;
int socket(int domain, int type, int protocol)
{
printf("calling mock socket\n");
return sock_rval;
}
Then in another file you have your test:
test_socket.c:
extern int sock_rval;
int get_socket();
int main()
{
sock_rval = -1;
int rval = get_socket();
assert(rval == -1);
sock_rval = 3;
int rval = get_socket();
assert(rval == 3);
return 0;
}
You would then compile and link these three modules together. Then `get_socket` will call the `socket` function in mock_socket.c instead of the library function.
This technique works not just with socket functions, but with system / library functions in general.