4

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?

satur9nine
  • 13,927
  • 5
  • 80
  • 123

2 Answers2

5

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.

xtofl
  • 40,723
  • 12
  • 105
  • 192
asn
  • 798
  • 9
  • 17
  • 1
    I don't understand your answer, why would I use #define to mock a function like strdup? The whole point of cmocka is that it allows me to mock functions in conjunction with the `--wrap` gcc option. I want to know how using cmocka I could mock strdup for one unit test and not mock it for a different unit test. – satur9nine Apr 21 '15 at 16:39
2

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.

satur9nine
  • 13,927
  • 5
  • 80
  • 123
  • 3
    This is not a nice solution. You should better do what @asn has written: 'compile without the -wrap command line option' – eDeviser Feb 07 '17 at 11:29