Function mocking (for testing) in C?

I wrote Mimick, a mocking/stubbing library for C functions that address this.

Assuming that square isn't static nor inline (because otherwise it becomes bound to the compilation unit and the functions that uses it) and that your functions are compiled inside a shared library named "libfoo.so" (or whatever your platform's naming convention is), this is what you would do:

#include <stdlib.h>
#include <assert.h>
#include <mimick.h>

/* Define the blueprint of a mock identified by `square_mock`
   that returns an `int` and takes a `int` parameter. */
mmk_mock_define (square_mock, int, int);

static int add_one(int x) { return x + 1; }

int main(void) {
    /* Mock the square function in the foo library using 
       the `square_mock` blueprint. */
    mmk_mock("square@lib:foo", square_mock);

    /* Tell the mock to return x + 1 whatever the given parameter is. */
    mmk_when(square(mmk_any(int)), .then_call = (mmk_fn) add_one);

    /* Alternatively, tell the mock to return 1 if called with 0. */
    mmk_when(square(0), .then_return = &(int) { 1 });

    assert(myfunction(0, 0) == 2);

    mmk_reset(square);
}

This is a full blown mocking solution though, and if you only want to stub square (and don't care about testing interactions), you could do something similar:

#include <stdlib.h>
#include <assert.h>
#include <mimick.h>

static int my_square(int x) { return x + 1; }

int main(void) {
    mmk_stub("square@lib:foo", my_square);

    assert(myfunction(0, 0) == 2);

    mmk_reset(square);
}

Mimick works by using some introspection on the running executable and poisoning at runtime the global offset table to redirect functions to the stub of our choice.


It looks like you are using GCC, so you can use the weak attribute:

The weak attribute causes the declaration to be emitted as a weak symbol rather than a global. This is primarily useful in defining library functions which can be overridden in user code, though it can also be used with non-function declarations. Weak symbols are supported for ELF targets, and also for a.out targets when using the GNU assembler and linker.

http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html


No, there's no solution for this. If there's a function in scope with a name matching a function call within a source file, that function will be used. No declaration trickery is going to talk the compiler out of it. By the time the linker is active, the name reference will have already been resolved.