satur9nine
satur9nine

Reputation: 15072

Correct way to temporarily enable and disable function wrapping in cmocka?

I am using the cmocka library to test some embedded c code. According to the documentation I use the __wrap_ prefix to mock functions so I can isolate my unit tests. However once I do that all calls to the function forever go to the wrapped function. How do I re-enable the real function in certain circumstances so I can test it or allow other functions to use it? It seems to me the only way is to use a global field as a switch to call the real function like so:

int __wrap_my_function(void) {
    if (g_disable_wrap_my_function) {
        return __real_my_function();
    }

    // ... do mock stuff
}

Is that the correct way to go about it?

Upvotes: 4

Views: 3110

Answers (2)

satur9nine
satur9nine

Reputation: 15072

I ended up doing exactly what I suggested in my question. I used a global variable that I check in the wrapped function to enable and disable the mocking at runtime.

Upvotes: 4

asn
asn

Reputation: 838

You simply compile without the -wrap command line option.

Or you use defines:

#include <cmocka.h>
#ifdef UNIT_TESTING
#define strdup test_strdup
#endif

Add the mock function test_strdup. You can now use this function to test.

Upvotes: 4

Related Questions