How can I test a function with void return value when using cunit

180 Views Asked by At

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?

1

There are 1 best solutions below

0
Zoyolin On

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 :

  • Create __stub_ functions to wrap the __real_ functions. These might be socket(), 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 to foo() by calls to __stub_foo(). The architecture I used to see for the foo_stub.c file is :
#include <xtypes>
#include "foo.h"
bool_t m_stubbed = FALSE;
void __stub_foo(void);
something foo_peek_value(void);
extern void __real_foo(void);
void __stub_foo(void){
if(m_stubbed){
   /* test code */
 }else{
   __real_foo();
 }
}
something foo_peek_value(void){
 return /* an interesting variable */
}

additionally call gcc with -Wl --wrap=foo.

  • Create a test file which setups the foo stub (by switching m_stubbed to true), make the test routine call foo(), and then check the outcome with a CU_ASSERT_EQUAL(foo_peek_value(), 42); (42 standing for the solution). Eventually add a teardown function to deactivate the stub.

Best of luck