Modern C++ • C++20 baseline
Unit Testing, Assertions, and Testable Design
Test observable behavior at boundaries and make core logic independent of hard-to-control systems.
Unit tests check small contracts; integration tests verify components working together. Assertions are useful for internal invariants during development but should not validate untrusted user input. Keep time, files, network access, and randomness behind interfaces when deterministic tests are important.
Key points
- Test normal, boundary, and failure cases.
- A passing test suite is evidence, not proof, that all behavior is correct.
Example
#include <cassert>
int clamp_score(int value) {
if (value < 0) return 0;
if (value > 100) return 100;
return value;
}
int main() {
assert(clamp_score(-1) == 0);
assert(clamp_score(50) == 50);
assert(clamp_score(101) == 100);
}
What to expect
All three assertions pass for the boundary and ordinary cases.
Practice exercise
Add a test for each branch and decide whether a table-driven test would be clearer.
Key idea: Design code so important behavior can be tested without relying on a particular environment.