Mocking: Stdout/stderr interception
Example: hello_world_intercepted_obj
When to use
Section titled “When to use”- You’d rather verify real output end to end than replace a function as simple as
putswith a mock. - You also want to check that nothing was written to stderr.
- You’re on a POSIX hosted system.
How it works
Section titled “How it works”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
stdoutandstderr; for each stream,dup()the original file descriptor, create apipe(), anddup2()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.
Step by step
Section titled “Step by step”-
Rename
mainin the compiled object:mocked_hello.o: hello.o$(OBJCOPY) --redefine-sym $(USER_LABEL_PREFIX)main=$(USER_LABEL_PREFIX)original_main $^ $@ -
Add the interceptor (
interceptor.h/interceptor.cfrom 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); -
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);}assertStrEqualsis a macro defined inhello_test.cthat prints expected and actual values to stderr and callsabort()on mismatch. -
Link and run:
hello_test: hello_test.o mocked_hello.o testcases.o interceptor.o $(ACEUNIT_LIBRARY)Run
makeinside the example directory.
Limitations
Section titled “Limitations”- Requires POSIX
dup(),dup2(),pipe(), andread(); 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(orllvm-objcopyon macOS) to renamemain.
Platform support
Section titled “Platform support”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.