0

Is it principally possible to mock the functions of a file to be tested?

E.g. I want to test the file self_test.c consisting of those functions:

#include "self_test.h"

uint8_t function_1(uint8_t argument)
{
    return function_2(argument);
}

uint8_t function_2(uint8_t argument)
{
    return (argument+1);
}

with the test file principally looking like this:

#include "mock_self_test.h"

void test_function_1(void)
{
    uint8_t input_value = 8;
    stest_function_2_ExpectAndReturn(input_value, 10);
    uint8_t output_value = function_1(input_value);
    TEST_ASSERT_EQUAL_UINT8(10, output_value);
}

and for completion the self_test.h file:

uint8_t function_1(uint8_t argument);
uint8_t function_2(uint8_t argument);

When I do this, the compiler returns: "error: Function function_1. Called more times than expected."

I suppose this is bad practice and may not work, but as my function_2 is rather large this could save me a ton of work since I can test function_1 idependently of function_2. And I am working on legacy code, so rewriting everything with a better testing interface is unfortunately not an option.

Ceedling output:

[==========] Running 1 tests from 1 test cases.
[----------] Global test environment set-up.
[----------] 1 tests from test_self_test.c
[ RUN      ] test_self_test.c.test_function_1
test_self_test.c(22): error: Function function_1.  Called more times than expected.
 Actual:   FALSE
 Expected: TRUE
[  FAILED  ] test_self_test.c.test_function_1 (0 ms)
[----------] 1 tests from test_self_test.c (0 ms total)
T.B.
  • 11
  • 4

1 Answers1

1

No, you can't mock functions that are called from the same compilation unit. Most compilers will not put a reference to the symbol of the called function but a direct (relocatable) address or offset into the generated machine code. They even can optimize the call away if possible.

You can cut the source files into smaller files which will be also a ton of work. You could try to automate this by a script.

Apparently the project to test has a bad software design. ;-)

the busybee
  • 10,755
  • 3
  • 13
  • 30