C++

Lesson 10

Unit tests for edge cases

Write C++ tests that assert edge cases directly instead of printing values for reviewers to inspect.

Good Code

tests/review_validation_test.cpp
#include <cassert>

void rejects_empty_title()
{
    // Test name and assertion capture the boundary case.
    assert(validate_review("", 80) == ReviewStatus::empty_title);
}

int main()
{
    rejects_empty_title();
}

Bad Code

tests/review_validation_test.cpp
#include <iostream>

int main()
{
    auto status = validate_review("", 80);

    // Printing the status makes CI pass even when the value is wrong.
    std::cout << static_cast<int>(status) << "\n";
}

Review Notes

What to review

Good Code

The good version names the edge case and asserts the exact status. CI fails when validation accepts an empty title or returns the wrong error.

Bad Code

The bad version prints the status and exits successfully. The test only works if a person reads the log and notices the wrong number.

Takeaways

  • A C++ test should encode the boundary expectation in assertions so CI can fail without human log reading.