Mocking: Compile-time macro
Example: hello_world_mocked_macro
When to use
Section titled “When to use”- You can compile the source under test a second time for the test build.
- You need maximum portability: this works with any C compiler that accepts
-D, including cross-compilers and toolchains withoutobjcopyor--wrap.
How it works
Section titled “How it works”The test build compiles hello.c into a separate object, mocked_hello.o, with two macro definitions. The preprocessor rewrites every occurrence of the identifiers before the compiler sees them:
mainbecomesoriginal_main, so AceUnit’smain()can run the tests.putsbecomesmocked_puts, a mock that records what would have been printed.
The production object hello.o is unaffected.
Step by step
Section titled “Step by step”Directoryhello_world_mocked_macro/
- hello.c code under test, unchanged
- hello_test.c the test
- mock_puts.c mock implementation
- mock_puts.h
assert_puts()helper - Makefile
-
Compile the code under test with the renaming macros:
mocked_hello.o: CPPFLAGS+=-Dputs=mocked_puts -Dmain=original_mainmocked_hello.o: hello.c$(COMPILE.c) $(OUTPUT_OPTION) $< -
Write the mock. It stores the text
puts()would have written (including the newlineputs()appends):mock_puts.c char mock_puts_buffer[BUF_SIZE];int mocked_puts(const char *text) {return snprintf(mock_puts_buffer, BUF_SIZE, "%s\n", text);}mock_puts.hprovides the assertion helper:mock_puts.h #define assert_puts(expected) \assert(strcmp(expected, mock_puts_buffer) == 0) -
Write the test. It calls the renamed
main:hello_test.c extern int original_main(void);void test_hello(void) {original_main();assert_puts("Hello, world!\n");} -
Generate the fixture from the test object and link everything with an AceUnit library:
hello_test: hello_test.o mock_puts.o mocked_hello.o testcases.o $(ACEUNIT_LIBRARY)testcases.c: hello_test.o$(ACEUNIT) $(ACEUNIT_FLAGS) $^ >$@ -
Run
make. Thetesttarget builds and runs./hello_test.
Limitations
Section titled “Limitations”- The source under test is compiled twice (once for production, once for tests).
- The macros apply to the whole translation unit, including any headers it includes. Every occurrence of the identifier is renamed, not only calls.
- Only calls made from the recompiled translation unit are redirected; other objects still call the real function.
Platform support
Section titled “Platform support”Any platform and compiler that supports -D macro definitions. The example is part of the default examples/Makefile build on all platforms.
See also: Mocking overview.