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

Principles of Unit Testing

Principles of Unit Testing

What you'll learn: You will learn how to isolate individual functions to ensure they work correctly in a vacuum before integrating them into a larger program.

The "Lego" Approach

Imagine you are building a complex Lego spaceship. If you wait until the entire ship is finished to check if the landing gear works, you might have to tear the whole thing apart to fix a tiny gear buried deep inside.

In C, Unit Testing is the practice of checking the smallest "units" of your code—usually individual functions—before they become part of the whole. If your calculate_tax() function works perfectly on its own, you can trust it when you plug it into a massive accounting suite.

The Three Pillars of a Test

A good unit test follows a simple pattern often called AAA:

  1. Arrange: Set up your inputs (e.g., define a variable x = 10).
  2. Act: Call the function you are testing and capture the result.
  3. Assert: Compare the result to what you expected. If they don't match, the test fails.

In C, we often use the <assert.h> library to perform these checks. If an assertion fails, the program crashes immediately, telling you exactly where the logic went wrong.

A Concrete Example

Let’s say we wrote a function to square an integer. We want to test it against positive numbers, negative numbers, and zero.

#include <stdio.h>
#include <assert.h>

// The "Unit" we are testing
int square(int n) {
    return n * n;
}

int main() {
    // Test 1: Positive numbers
    assert(square(5) == 25);

    // Test 2: Negative numbers
    assert(square(-3) == 9);

    // Test 3: Zero
    assert(square(0) == 0);

    printf("All unit tests passed successfully!\n");
    return 0;
}

Why Bother?

It feels like extra work now, but unit tests are your "safety net." If you decide to optimize your square function later to make it faster, you can re-run your tests instantly. If the tests pass, you know your changes didn't break the core logic. This gives you the confidence to refactor code without the fear of invisible bugs.

Key takeaway

Unit testing isolates single functions to catch bugs early, using assertions to verify that specific inputs produce expected outputs.