c++cunit-testingcpputest

Is any way to mock global variable in CppUTest?


Is there any way to mock static global variable to use in test function? Or any workaround for that?

Below example of such situation:

static zsock_t *publish_logs =  NULL;

int btak_log_message_reactor(zloop_t *loop, zsock_t *reader, void *arg) {
    struct btak_log_message *message;
    size_t message_size;

    if(zsock_recv(reader, "b", &message, &message_size) == 0) {
        push_log_message(message);
        if(publish_logs)
            publish_log_message(message, publish_logs);
        free(message);
    }

    return 0;
}

Solution

  • We often forget about the linker. We can use a different object file to mock an interface. This mock-obj would contain a different definition of your global.

    But current unit test frameworks only work on code level... So some build-fu will be needed to add mock objects to the test build.