Skip to content

Mocking: Stdout/stderr interception

Example: hello_world_intercepted_obj

  • You’d rather verify real output end to end than replace a function as simple as puts with a mock.
  • You also want to check that nothing was written to stderr.
  • You’re on a POSIX hosted system.

puts() isn’t mocked at all. Only main is renamed to original_main with objcopy. A small Interceptor helper (interceptor.c) captures the output:

  • Start: flush stdout and stderr; for each stream, dup() the original file descriptor, create a pipe(), and dup2() the pipe’s write end over the stream.
  • Stop: flush again; restore the original descriptor, close the write end, read() what was written into the caller’s buffer (NUL-terminated), and close the remaining descriptors.
  1. Rename main in the compiled object:

    mocked_hello.o: hello.o
    $(OBJCOPY) --redefine-sym $(USER_LABEL_PREFIX)main=$(USER_LABEL_PREFIX)original_main $^ $@
  2. Add the interceptor (interceptor.h / interceptor.c from the example):

    interceptor.h
    typedef struct Interceptor Interceptor;
    Interceptor *Interceptor_start(void);
    extern void Interceptor_stop(Interceptor **self, char *stdoutBuffer, size_t stdoutBufferSize, char *stderrBuffer, size_t stderrBufferSize);
  3. Write the test:

    hello_test.c
    extern int original_main(void);
    void test_hello(void) {
    Interceptor *interceptor = Interceptor_start();
    int exitStatus = original_main();
    char stdoutBuffer[4096];
    char stderrBuffer[4096];
    Interceptor_stop(&interceptor, stdoutBuffer, sizeof(stdoutBuffer), stderrBuffer, sizeof(stderrBuffer));
    assert(0 == exitStatus);
    assertStrEquals("Hello, world!\n", stdoutBuffer);
    assertStrEquals("", stderrBuffer);
    }

    assertStrEquals is a macro defined in hello_test.c that prints expected and actual values to stderr and calls abort() on mismatch.

  4. Link and run:

    hello_test: hello_test.o mocked_hello.o testcases.o interceptor.o $(ACEUNIT_LIBRARY)

    Run make inside the example directory.

  • Requires POSIX dup(), dup2(), pipe(), and read(); not for freestanding/embedded targets.
  • Output is read only after the code under test returns, so it must fit into the pipe’s buffer; output beyond the pipe capacity would block the writer. Only as much as fits into the caller’s buffer (minus one byte for the terminator) is read.
  • The example’s interceptor calls abort() if a system call fails.
  • Still needs objcopy (or llvm-objcopy on macOS) to rename main.

POSIX hosted systems with objcopy/llvm-objcopy. Note: this example isn’t listed in the default examples/Makefile, so run make in its own directory.

See also: Mocking overview, objcopy override, which mocks puts directly.