What You'll Learn

    • Write assertion-based unit tests
    • Test fixtures for repeatable setup
    • Test-Driven Development (TDD) workflow
    • GoogleTest, Catch2, Doctest overview

    C++ Unit Testing

    Unit tests verify that individual functions and classes work correctly in isolation. They catch bugs early, document expected behavior, and give you confidence to refactor. This lesson covers writing tests from scratch, test fixtures, and TDD — the professional development workflow.

    Writing Basic Tests

    A test calls a function with known inputs and checks the output against expected values. If the output matches, the test passes. Group related tests together and return a non-zero exit code if any test fails — CI systems use this to detect broken builds.

    Pro Tip: Test edge cases first: empty inputs, zero, negative numbers, maximum values. Most bugs hide in boundaries, not in the happy path.

    Basic Unit Tests

    Test factorial, average, and isPrime functions

    Try it Yourself »
    C++
    #include <iostream>
    #include <string>
    #include <vector>
    #include <cmath>
    using namespace std;
    
    // Simple test framework (like a mini Catch2)
    int testsPassed = 0, testsFailed = 0;
    
    void CHECK(bool condition, const string& name) {
        if (condition) {
            cout << "  ✓ " << name << endl;
            testsPassed++;
        } else {
            cout << "  ✗ FAILED: " << name << endl;
            testsFailed++;
        }
    }
    
    void CHECK_EQUAL(int actual, int expected, const string& name) {
        CHECK(actual == expected,
    ...

    Test Fixtures — Repeatable Setup

    A fixture creates a known starting state before each test. Instead of duplicating setup code, call a factory function that returns a fresh object. Each test gets its own copy — no test can pollute another.

    Common Mistake: Sharing mutable state between tests. If test A modifies a shared object, test B may pass or fail depending on execution order. Always use fresh fixtures.

    Test Fixtures

    Test a ShoppingCart class with fresh fixtures

    Try it Yourself »
    C++
    #include <iostream>
    #include <vector>
    #include <string>
    #include <algorithm>
    using namespace std;
    
    int testsPassed = 0, testsFailed = 0;
    void REQUIRE(bool cond, const string& msg) {
        if (cond) { cout << "  ✓ " << msg << endl; testsPassed++; }
        else { cout << "  ✗ FAIL: " << msg << endl; testsFailed++; }
    }
    
    // Class under test
    class ShoppingCart {
        struct Item { string name; double price; int qty; };
        vector<Item> items;
    public:
        void add(const string& name, double price, int qty =
    ...

    Test-Driven Development (TDD)

    TDD flips the process: write the test first, watch it fail, then write the minimum code to make it pass. This ensures every feature has test coverage and forces you to think about the interface before the implementation.

    TDD: Password Validator

    Write tests first, then implement the validator

    Try it Yourself »
    C++
    #include <iostream>
    #include <string>
    #include <vector>
    #include <sstream>
    using namespace std;
    
    int passed = 0, failed = 0;
    void ASSERT(bool c, const string& m) {
        if (c) { cout << "  ✓ " << m << endl; passed++; }
        else { cout << "  ✗ " << m << endl; failed++; }
    }
    
    // TDD: Write tests FIRST, then implement
    
    // Step 1: Define interface (what we want)
    class PasswordValidator {
        int minLength;
        bool requireDigit;
        bool requireUpper;
    public:
        PasswordValidator(int minLen = 8, bool
    ...

    Quick Reference

    FrameworkSetupAssert
    GoogleTestTEST(Suite, Name)EXPECT_EQ, ASSERT_TRUE
    Catch2TEST_CASE("name")REQUIRE, CHECK
    DoctestTEST_CASE("name")CHECK, REQUIRE

    Lesson Complete!

    You can now write unit tests, use fixtures, and follow TDD to build reliable C++ software.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service