Skip to content

Examples

AceUnit ships worked examples in share/doc/aceunit/examples (the repository’s top-level examples is a symlink to it). They’re also installed with AceUnit under share/doc/aceunit/examples.

  • Directoryexamples/
    • Directoryleapyear/ start here: a pure function, built against the source tree
      • …
    • Directoryinstalled/ the same example, built against an installed AceUnit
      • …
    • Directoryinstalled.mk/ the same, using the aceunit.mk include
      • …
    • Directoryhello_world_mocked_macro/ mock via preprocessor macros
      • …
    • Directoryhello_world_mocked_obj/ mock via objcopy symbol renaming
      • …
    • Directoryhello_world_mocked_link/ mock via linker --wrap
      • …
    • Directoryhello_world_mocked_interpose/ mock via dyld interposing (macOS)
      • …
    • Directoryhello_world_intercepted_obj/ capture real stdout/stderr
      • …
    • Makefile builds the default set

From the examples directory, make builds and runs leapyear, hello_world_mocked_macro, hello_world_mocked_obj, plus hello_world_mocked_interpose on Darwin or hello_world_mocked_link elsewhere. Every other example runs with make inside its own directory.

The in-tree examples expect AceUnit to be built first (they reference bin/aceunit, include/, and lib/libaceunit-fork.a relative to the source tree).

leapyear is the entry point. It tests a single module without a main() function, and the function under test is pure (no side effects) and a leaf (calls nothing else) — the situation where unit testing is easy.

leapyear_test.c
void testLeapYears() {
assert(isLeapYear(0));
assert(isLeapYear(4));
assert(isLeapYear(400));
}
void testNonLeapYears() {
assert(!isLeapYear(1));
assert(!isLeapYear(100));
}

The Makefile shows the core AceUnit workflow: compile the test, let aceunit generate testcases.c from the test object file, and link with an AceUnit runner library:

leapyear_test: leapyear_test.o leapyear.o testcases.o $(ACEUNIT_LIBRARY)
testcases.c: leapyear_test.o
$(ACEUNIT) $(ACEUNIT_FLAGS) $^ >$@

Using an installed AceUnit: installed and installed.mk

Section titled “Using an installed AceUnit: installed and installed.mk”
  • installed builds the leap-year example against a system-wide installation: ACEUNIT:=aceunit and LOADLIBES:=-laceunit-fork.

  • installed.mk does the same but includes aceunit.mk, which defines ACEUNIT, ACEUNIT_FLAGS, and the recipe variable ACEUNIT.o, so the generator rule shrinks to:

    testcases.c: leapyear_test.o
    $(ACEUNIT.o)
    include aceunit.mk

The hello_world_* examples unit-test a plain hello.c that was not prepared for testability. Each must (1) move the program’s main() aside so AceUnit’s runner can own main(), and (2) deal with the puts() side effect by mocking or intercepting it. All of them build without changing hello.c.

Use the mocking overview to pick the right technique for your toolchain.