Skip to content

Mocking: Compile-time macro

Example: hello_world_mocked_macro

  • 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 without objcopy or --wrap.

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:

  • main becomes original_main, so AceUnit’s main() can run the tests.
  • puts becomes mocked_puts, a mock that records what would have been printed.

The production object hello.o is unaffected.

  • 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
  1. Compile the code under test with the renaming macros:

    mocked_hello.o: CPPFLAGS+=-Dputs=mocked_puts -Dmain=original_main
    mocked_hello.o: hello.c
    $(COMPILE.c) $(OUTPUT_OPTION) $<
  2. Write the mock. It stores the text puts() would have written (including the newline puts() 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.h provides the assertion helper:

    mock_puts.h
    #define assert_puts(expected) \
    assert(strcmp(expected, mock_puts_buffer) == 0)
  3. 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");
    }
  4. 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) $^ >$@
  5. Run make. The test target builds and runs ./hello_test.

  • 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.

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.