Mocking 🔗

Simulate the behavior of a function.

Macros 🔗

#define FAKE(
FUNC, FAKE)

Redirects all function calls to a mock function.

#define STUB(
FUNC, VALUE)

Stub a function so it always returns a specific value.

#define CALL(
FUNC, ...)

Call the original function being mocked.

#define CALL_GET(
FUNC, RESULT, ...)

Call the original function being mocked and save its return value.

#define RESTORE(
FUNC)

Remove a previously registered mock.

#define SUSPEND_MOCKS(
)

Suspend all mocks.

#define RESTORE_MOCKS(
)

Restore all mocks.

Discussion 🔗

Function mocking is the practice of creating a simulated version of a function to control its behavior and isolate the code being tested, allowing for more effective unit testing. The benefits of mocking include improved test isolation, greater control over the test environment, and faster execution by avoiding real resource interactions.

The following code example demonstrates how to use mocks to hard code the return value of a function. In this example the function foo is hard coded to always return the value 42.

TEST(spam, eggs) {
    STUB(foo, 42);              // mocks foo()
    printf("foo: %d\n", foo()); // prints 42
}

Mocking is discussed extensively in the Mocking Functions guide.