I have a function that I need to test with cunit. The function looks like this:
void server(unsigned short port) {
int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if (sock_fd < 0) {
perror("server: socket");
exit(1);
}
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = INADDR_ANY;
memset(&server.sin_zero, 0, 8);
if (bind(sock_fd, (struct sockaddr *)&server, sizeof(server)) < 0) {
perror("server: bind");
close(sock_fd);
exit(1);
}
if (listen(sock_fd, MAX_BACKLOG) < 0) {
perror("server: listen");
close(sock_fd);
exit(1);
}
......
}
How can I test this function using cunit?
As busy bee said, this function, does something which is even more important than the value it might have returned. I don't have a lot of experience but here is what I'd do :
__stub_functions to wrap the__real_functions. These might besocket(),perror(),exit(),memset(),bind(),close(),listen(). you probably don't need them all so ask your self which matters. you can litterally wrap any function (with gcc at least) which means substitute all calls tofoo()by calls to__stub_foo(). The architecture I used to see for thefoo_stub.cfile is :additionally call gcc with
-Wl --wrap=foo.m_stubbedto true), make the test routine call foo(), and then check the outcome with aCU_ASSERT_EQUAL(foo_peek_value(), 42);(42 standing for the solution). Eventually add a teardown function to deactivate the stub.Best of luck