0

I want to implement unit testing using the -Wl,--wrap trick, however this doesn't work for functions within the same file. One solution is to rename the function (after it has been defined) to the wrapped one, as suggested here: https://stackoverflow.com/a/11758777/526568

I came up with the following macro to avoid having to manually define __wrap_foo:

#define UNIT_TEST_SYMBOL(x) \
    typeof(x) __wrap_##x __attribute__((weak, alias(#x)))

void foo(void) {
    /* function body */
}
UNIT_TEST_SYMBOL(foo);

#define foo __wrap_foo

void bar(void) {
    foo();
}

I then compile with -Wl,--wrap=foo.

Is it possible to avoid having to manually define foo to __wrap_foo? Can this be somehow part of the UNIT_TEST_SYMBOL?

Thanos
  • 691
  • 1
  • 5
  • 14
  • https://github.com/Guardsquare/mocxx – Maxim Egorushkin Nov 26 '20 at 16:11
  • @MaximEgorushkin does it work for plain old C? – Thanos Nov 26 '20 at 16:43
  • Also mocxx fails to build. – Thanos Nov 26 '20 at 16:54
  • I think, since local functions in the same translation unit are resolved at compile time, the linker has no chance to intercept. I would try to work on the source level, perhaps with some kind of separated preprocessing tool. Another idea is to separate the functions in different translation units. – the busybee Nov 27 '20 at 07:03
  • However, unit testing is about testing the **_unit_**. And I think that local functions are just a part of a unit, and should therefore not be tested in isolation. -- This is a common misunderstanding in my eyes, to test functions, and not functionality, vulgo requirements. -- You might like to consider to post your use case to help us understand the issue. – the busybee Nov 27 '20 at 07:06
  • @thebusybee It depends on how you define the "unit", it's not set to stone that a unit is the source file. In Python you can trivially mock and unit test functions _within_ the same source file. – Thanos Nov 27 '20 at 09:48

0 Answers0