Integration testing vs. Unit testing
What you'll learn: How to distinguish between testing individual functions in isolation and testing how those functions work together as a complete system.
The Tool vs. The Machine
Imagine you are building a clock.
Unit testing is like checking a single gear. You hold it up, count the teeth, and make sure it’s not bent. You don't care about the rest of the clock yet; you just want to know if this specific part does its job perfectly. In C, this means testing one function (the "unit") with various inputs to ensure the output is exactly what you expect.
Integration testing is like putting three gears together and turning the first one to see if the third one moves. Even if every gear is perfect, they might not fit together, or the spacing might be wrong. In C, this means testing how different modules or files interact—for example, checking if your database_save() function correctly handles the data passed to it by your user_input() function.
Code Comparison
In a unit test, we isolate. In an integration test, we flow.
#include <assert.h>
// The "Units"
int add(int a, int b) { return a + b; }
int square(int n) { return n * n; }
// The "Integrated" Logic
int sum_then_square(int a, int b) {
int sum = add(a, b);
return square(sum);
}
void run_tests() {
// UNIT TESTS: Testing parts in isolation
assert(add(2, 2) == 4);
assert(square(3) == 9);
// INTEGRATION TEST: Testing the hand-off between parts
// We are ensuring 'add' feeds correctly into 'square'
assert(sum_then_square(1, 2) == 9);
}
int main() {
run_tests();
return 0;
}
Why do both?
You might wonder: "If I test every single function, isn't the whole program guaranteed to work?"
Unfortunately, no. Most bugs in complex C programs happen in the "hand-off." One programmer might write a function that returns 0 for success, while another programmer writes a function expecting 1 for success. Both functions work perfectly according to their own logic (Unit Test: Pass!), but when they talk to each other, the program crashes (Integration Test: Fail!).
Unit tests give you confidence in your logic; integration tests give you confidence in your architecture.
Key takeaway
Unit testing checks if your individual bricks are solid; integration tests check if the bricks actually fit together to form a wall.