Cmock doesn't recognise function calls

3k Views Asked by At

I'm new to Cmock a mocking framework in C, and trying to start using it. I took the 'make_example' supplied in the exmaples dir and modified it a bit. My code is appearing underneath:

/////////////////////////// foo.c ///////////////////////////
#include "foo.h"

int foo_init(int number)
{
    return 0;
}

int func_using_foo_init(int number)
{
    int ret = -1;

    ret = foo_init(number);
    return ret;
}
//////////////////////////////////////////////////////

/////////////////////////// test_main.c ///////////////////////////

#include "unity.h"
#include "mock_foo.h"

void setUp(void)
{
}

void tearDown(void)
{
}

void test_main_should_initialize_foo(void)
{
    int ret = -1;
    foo_init_ExpectAndReturn(1, 0);

    ret = func_using_foo_init(1);
    TEST_ASSERT_FALSE(ret);
}
//////////////////////////////////////////////////////

when running the shown test, i'm getting the next error: FAIL:Function func_using_foo_init. Called more times than expected.

in addition if i'm adding a call to func_using_foo_init_ExpectAndReturn, i'm getting the next error: Function foo_init. Called less times than expected.

seems like function calls are not recognized.. any help will be highly appreciated ! liad

1

There are 1 best solutions below

0
On

A mock is generated code that has the same function signature as the function you’re mocking. A consequence is that you cannot have the mocked function and the original real function compiled and linked together in the same test executable. C only knows how to compile and link entire source files. It can’t pick and choose functions inside modules to mix together.

Put simply, this means you can’t make mocked calls to a function that’s inside the same source file you’re trying to test. This is a fundamental rule of interaction-based testing in C. On the whole this leads to better design (especially in large projects), but it does have the side effect of more files (go with longer descriptive file names) and sometimes arbitrary divisions of code among files to enable mocking.

Hence the best advice it to carve out foo_init() to be in a separate file from test_using_foo_init().

Generally speaking, any one test executable will consist of a single source module and one or more mocked modules whose function signatures are all outside the source you’re testing. In the simplest case you need at least two distinct modules (one source and one mocked) to test with mocks.