Course contentsShow
← C
Lesson 1176 of 1,21916. Practice and ProjectsFree lesson

Mocking simple dependencies

Mocking simple dependencies

What you'll learn: How to isolate the code you are testing by replacing complex functions with simple "fake" versions called mocks.

The Problem: The "Messy" Neighbor

Imagine you are testing a function that calculates if a plane should land. To work, this function calls get_wind_speed(). If get_wind_speed() connects to a real weather sensor that is currently broken or fluctuating, your test will fail—even if your landing logic is perfect.

In C, we want to test our logic in a vacuum. We don’t want a bug in a database, a sensor, or a network connection to ruin our local tests.

Enter the Mock

A mock is a "stunt double." It has the exact same name and signature as the real function, but instead of doing hard work, it returns a hard-coded value that you control.

To do this simply in C, we often use Linker Substitution. We tell the compiler: "When building the test, don't use the real sensor.c file; use my mock_sensor.c file instead."

Seeing it in Action

Suppose we are testing a security system. The real function is_door_locked() checks physical hardware. In our test, we want it to just say "Yes."

/* logic.c - The code we are testing */
extern int is_door_locked(); // Defined elsewhere

const char* check_security_status() {
    if (is_door_locked()) {
        return "System Secure";
    }
    return "ALARM";
}

/* mock_sensor.c - The "Stunt Double" */
// We define the function here so the linker finds this version first
int is_door_locked() {
    return 1; // Always returns "Locked" for this specific test
}

/* test_main.c */
#include <stdio.h>
#include <assert.h>
#include <string.h>

int main() {
    // Because our mock returns 1, this should always pass
    assert(strcmp(check_security_status(), "System Secure") == 0);
    printf("Test passed using mock!\n");
    return 0;
}

Why this helps

By using a mock, you gain two superpowers:

  1. Predictability: You know exactly what the dependency will return every time.
  2. Edge Case Testing: You can write a mock that returns an error code (like -1) to see if your program crashes, without having to actually break your hardware.

When you compile your test, you simply link logic.c and test_main.c with your mock_sensor.c instead of the real hardware driver.

Key takeaway

Mocking replaces unpredictable dependencies with controlled "fake" functions so you can test your logic in isolation.