Skip to content

Testing basics

Difficulty: Beginner

Key concepts

  • unit test
  • assertion
  • test harness
  • arrange act assert
  • boundary value
  • failure path
  • CTest
  • test label
  • What a small, automated test is, and how this site’s test harness works.
  • How to structure a test as arrange, act, assert.
  • Which inputs are worth testing: boundaries and failure paths.
  • How to run tests with CTest, choose which ones run, and read a failure.

A design makes promises: “the fee never exceeds $10”, “a loan on hold cannot be renewed”. A test is one of those promises written as code that checks itself. Tests matter to design in three ways:

  • They pin down behaviour, so a later change that breaks a promise fails at once, instead of in front of a member.
  • They show how the code is meant to be used, as examples that cannot go out of date, because they run on every build.
  • They push the design toward small, clear parts. Code that is hard to test usually has too many responsibilities or hidden dependencies. Later lessons return to this.

This page covers the simplest kind: a unit test, which calls one function or class directly and checks the result, with no files, network, or user involved.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

loan_rules.hpp
// The numbers the rules depend on, gathered in one plain struct so a test
// (or a different library) can pass in its own. Each member has a default
// value, so `LoanPolicy policy;` or `LoanPolicy{}` gives the standard policy,
// and a test can change just the fields it cares about.
struct LoanPolicy {
int loan_days = 21; // length of one loan period
int max_renewals = 2; // renewals allowed per loan
int fee_per_day_cents = 25; // late fee per day; must be > 0
int fee_cap_cents = 1'000; // late fee never exceeds this
};
// Late fee for returning days_late days after the due date: 0 if on time or
// early, otherwise fee_per_day_cents per day, capped at fee_cap_cents.
[[nodiscard]] int late_fee_cents(const LoanPolicy& policy, int days_late);
// Whether a loan may be renewed. A loan with a hold from another member
// cannot be renewed. Throws std::invalid_argument if renewals_so_far < 0.
[[nodiscard]] bool can_renew(const LoanPolicy& policy, int renewals_so_far, bool has_hold);
// Days until the item is due when the loan has been renewed renewals times,
// counted from the day it was first borrowed: loan_days * (renewals + 1).
[[nodiscard]] int days_allowed(const LoanPolicy& policy, int renewals);

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

loan_rules.cpp
// Three cases, in order: on time (no fee), so late the cap applies, and
// otherwise the daily fee times the days, still never above the cap. Like
// the other rules, it takes the policy by const reference: read, not copied.
int late_fee_cents(const LoanPolicy& policy, int days_late) {
if (days_late <= 0) return 0;
// Compare in days first, so a large days_late cannot overflow the
// multiplication.
// fee_cap_cents / fee_per_day_cents is the most days that still fit
// under the cap (1000 / 25 = 40 with the defaults; integer division
// rounds 120 / 50 down to 2). It divides by fee_per_day_cents, which is
// why the policy requires that to be > 0. Beyond that many days, the fee
// is the cap, and days_late is never multiplied.
if (days_late > policy.fee_cap_cents / policy.fee_per_day_cents) {
return policy.fee_cap_cents;
}
// Here days_late is at most cap / fee, so days_late * fee_per_day_cents
// is at most the cap and fits in an int. std::min returns the smaller of
// the two; after the check above it never changes the result, but it
// states the rule "never above the cap" in the line that computes the fee.
return std::min(days_late * policy.fee_per_day_cents, policy.fee_cap_cents);
}
// A negative count is a caller's bug, so it throws. Otherwise both
// conditions must hold: `!has_hold` (nobody else is waiting) and a renewal
// left. With max_renewals = 2, counts 0 and 1 may renew; 2 may not.
bool can_renew(const LoanPolicy& policy, int renewals_so_far, bool has_hold) {
if (renewals_so_far < 0) throw std::invalid_argument("renewals cannot be negative");
return !has_hold && renewals_so_far < policy.max_renewals;
}
// The first loan period, plus one more for each renewal: 21, 42, 63, ...
// It does not check `renewals`; can_renew decides whether a renewal is allowed.
int days_allowed(const LoanPolicy& policy, int renewals) {
return policy.loan_days * (renewals + 1);
}
How this code works: late_fee_cents

The obvious version is one line: std::min(days_late * fee, cap). The real version adds one check, so that the multiplication can never overflow.

  1. On time. days_late <= 0 means the item came back on or before the due date, so the fee is 0.
  2. The overflow guard. fee_cap_cents / fee_per_day_cents is the largest number of days whose fee still fits under the cap: with the defaults, 1000 / 25 is 40. More days than that, and the answer is simply the cap. Because this returns before multiplying, a huge days_late such as INT_MAX is never multiplied by 25.
  3. The ordinary case. Only days_late from 1 to 40 (with the defaults) gets here, so days_late * 25 is at most 1000 and fits easily in an int.

With the default policy (25 cents a day, cap 1000):

days_late Step that answers Calculation Fee
-1 1 on time 0
3 3 3 × 25 75
39 3 39 × 25 975
40 3 40 is not more than 40: 40 × 25 1000
41 2 41 is more than 40 1000
INT_MAX 2 more than 40, no multiplying 1000

With the test’s strict policy (50 cents a day, cap 120), 120 / 50 is 2, because integer division drops the fraction. Day 2 costs 100; day 3 is more than 2, so it costs the cap, 120.

can_renew and days_allowed are one line each. can_renew refuses a negative count with an exception, because that is a caller’s bug, and otherwise needs both “no hold” and “a renewal left”.

The rules are plain functions on values: a LoanPolicy goes in, a number or a bool comes out. Nothing is read from a clock or a database. That is a design choice, and it is what makes the rules easy to test: a test can pass in any policy and any number of days.

Every test on this site uses a small header, lld_test.hpp, written for this site so that the examples need nothing beyond a compiler and CMake. It provides four macros:

  • LLD_TEST(name) { … } defines a test, and registers it to be run.
  • LLD_CHECK(condition) records a failure if the condition is false.
  • LLD_CHECK_EQ(actual, expected) records a failure if the two are not equal, and prints both. Both must be printable with <<.
  • LLD_CHECK_THROWS(expression, ExceptionType) records a failure unless the expression throws that exception type.

A failed check does not stop the test: the remaining checks still run, so one run reports every failure. The test program’s main, in the harness, runs every registered test, catches any exception a test lets escape (and counts it as a failure), prints a summary, and exits with status 1 if anything failed, or 0 if nothing did.

Real projects usually use a test framework such as GoogleTest or Catch2, which add many features: fixtures, parameterised tests, richer messages. The ideas on this page are the same with any of them.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_loan_rules.cpp
// LLD_TEST(name) { ... } defines one test and registers it, so the test
// program runs it. LLD_CHECK_EQ(actual, expected) records a failure, and
// prints both values, if they are not equal. Both come from lld_test.hpp.
LLD_TEST(late_fee_grows_by_the_day) {
// Arrange: the inputs, including any policy the rule depends on.
const LoanPolicy policy; // defaults: 25 cents a day, capped at $10
const int days_late = 3;
// Act: exactly one call to the behaviour under test.
const int fee = late_fee_cents(policy, days_late);
// Assert: the observable result. 3 days * 25 cents = 75 cents.
LLD_CHECK_EQ(fee, 75);
}

Most good unit tests have three parts, in this order:

  1. Arrange: set up the inputs and any objects the behaviour needs.
  2. Act: do the one thing being tested.
  3. Assert: check the observable result.

Keeping the parts separate makes a test easy to read: you can see what was given, what was done, and what was expected. If a test seems to need several “act” steps, it is usually testing several behaviours, and should be split into several tests. Short tests often fit the three parts on a few lines without comments, as the next tests do.

The test’s name says what behaviour it checks, in words: late_fee_grows_by_the_day. When it fails, the name is the first clue.

Testing late_fee_cents(policy, 3) checks one ordinary value. Bugs are rarely in the middle of a range. They hide at the edges: < written instead of <=, a limit off by one. So test the boundaries: each limit, and the values just inside and just outside it.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_loan_rules.cpp
// Each edge of late_fee_cents with the default policy (25 a day, cap 1000,
// so the cap is reached on day 40), plus the largest int, which would
// overflow if it were multiplied by 25. INT_MAX comes from <climits>.
LLD_TEST(late_fee_boundaries) {
const LoanPolicy policy;
LLD_CHECK_EQ(late_fee_cents(policy, -1), 0); // returned early
LLD_CHECK_EQ(late_fee_cents(policy, 0), 0); // returned on the due date
LLD_CHECK_EQ(late_fee_cents(policy, 1), 25); // first late day
LLD_CHECK_EQ(late_fee_cents(policy, 39), 975); // last day below the cap
LLD_CHECK_EQ(late_fee_cents(policy, 40), 1000); // exactly at the cap
LLD_CHECK_EQ(late_fee_cents(policy, 41), 1000); // past the cap
LLD_CHECK_EQ(late_fee_cents(policy, INT_MAX), 1000); // no overflow
}
// LLD_CHECK(condition) records a failure if the condition is false; with
// `!` in front, it checks that the answer is "no".
LLD_TEST(renewal_limit_boundaries) {
const LoanPolicy policy; // max_renewals = 2
LLD_CHECK(can_renew(policy, 0, false));
LLD_CHECK(can_renew(policy, 1, false)); // last allowed renewal
LLD_CHECK(!can_renew(policy, 2, false)); // limit reached
}

For the late fee, the edges are:

  • On time: 0 days late (the due date itself), and a negative value (returned early).
  • The first late day: 1.
  • The cap: 39 days is the last below $10, 40 reaches it exactly, and 41 is past it. With 25 cents a day, the cap of 1000 cents is reached at exactly 40 days, which is where an off-by-one mistake would show.
  • An extreme value: INT_MAX days. Multiplying it by 25 would overflow an int, so the implementation compares with the cap first. The build-basics lesson showed what happens without that guard: UndefinedBehaviorSanitizer reported the overflow in a similar function. This test runs in the site’s sanitizer build too, so a regression would be reported there.

For renewals, the limit is two: 1 renewal so far is the last that may renew, and 2 is the first that may not.

A failure path is any way the code says “no”: a refused request, a rejected input, an exception. These paths run rarely in normal use, so they are easy to leave untested, and their bugs are found late.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_loan_rules.cpp
// LoanPolicy{} creates a default policy on the spot, for this call only.
// Even with no renewals used, a hold means "no".
LLD_TEST(a_hold_blocks_renewal) {
LLD_CHECK(!can_renew(LoanPolicy{}, 0, true));
}
// LLD_CHECK_THROWS(expression, type) fails unless the expression throws an
// exception of that type: the header's promise for a negative count.
LLD_TEST(negative_renewals_are_rejected) {
LLD_CHECK_THROWS(can_renew(LoanPolicy{}, -1, false), std::invalid_argument);
}
// A policy with no renewals, 50 cents a day, and a 120-cent cap. 120 / 50
// is 2, so day 2 costs 2 * 50 = 100 and day 3 is past the limit: the cap.
LLD_TEST(rules_follow_a_custom_policy) {
LoanPolicy strict;
strict.max_renewals = 0;
strict.fee_per_day_cents = 50;
strict.fee_cap_cents = 120;
LLD_CHECK(!can_renew(strict, 0, false));
LLD_CHECK_EQ(late_fee_cents(strict, 2), 100);
LLD_CHECK_EQ(late_fee_cents(strict, 3), 120); // cap is not a multiple of the daily fee
}
  • a_hold_blocks_renewal checks a refusal: the rule says “no” for a business reason.
  • negative_renewals_are_rejected checks a documented error: the header promises std::invalid_argument for a negative count, so the test holds the code to that promise.
  • rules_follow_a_custom_policy checks that the rules use the policy they are given rather than the default numbers, including a cap (120 cents) that is not a multiple of the daily fee (50 cents).

A useful habit: for each sentence in a function’s header comment, ask “which test would fail if this sentence stopped being true?”

The example’s CMakeLists.txt registers the test program with CTest, CMake’s test runner. It also gives the test a label, a tag for choosing groups of tests:

lld_add_test(testing_loan_rules_tests SOURCES test_loan_rules.cpp LABELS loan-rules)

lld_add_test is the site’s helper. It builds the program, links the harness, and calls add_test. In the build directory:

Terminal window
ctest # run every test
ctest -R loan_rules # only tests whose name matches a regular expression
ctest -L loan-rules # only tests with this label
ctest --output-on-failure # show a failing test's own output

By default, CTest shows only “Passed” or “Failed” for each test. To see why a test failed, add --output-on-failure. Here is a real run of ctest --output-on-failure, on this machine, of a temporary copy of the tests in which one expected value was deliberately changed from 1000 to 975:

1/1 Test #1: testing_loan_rules_tests .........***Failed 0.00 sec
actual: 1000
expected: 975
…/test_loan_rules.cpp:42: check failed: late_fee_cents(policy, 40) == 975
7 test(s), 1 failure(s)
0% tests passed, 1 tests failed out of 1

The four lines after ***Failed are the test program’s own output: the actual and expected values, then the file, line, and expression that failed, and the harness’s summary. Plain ctest shows only the ***Failed line and CTest’s summary. The site’s CMake test presets, as in ctest --preset gcc-debug, turn this on automatically.

Read a failure in this order: which check (file and line), what was expected, what happened. Then decide which one is wrong. Here the test was wrong; the next time it may be the code.

  • Test behaviour, not implementation. Check what a function returns or what an object reports, not which private helper it called. Then the implementation can be improved without rewriting the tests.
  • One behaviour per test. A test named after one rule, with one reason to fail, is easy to diagnose.
  • Tests must be repeatable. A unit test should give the same result every time, on every machine: no real clock, no random numbers without a fixed seed, no dependence on the order tests run in.
  • Do not test the standard library or the compiler. Trust that std::min works; test that your cap logic uses it correctly.
  • Only testing the “happy path”. The boundaries and refusals are where the bugs are.
  • Several unrelated behaviours in one test. When it fails, the name does not say which.
  • Copying the implementation’s arithmetic into the test. If the test computes days * policy.fee_per_day_cents, it repeats any mistake in the code. Write the expected number (75) directly.
  • Tests that depend on each other. Each test should arrange everything it needs.
  • Never seeing a new test fail. It may not be testing anything.

New requirement: “Children’s accounts have no late fees.”

A good way to handle a rule change is to start with a test that expresses the new promise. Here the change may not need new code at all: the header promises that the fee never exceeds fee_cap_cents, so a children’s LoanPolicy with fee_cap_cents = 0 charges nothing. The test is one line, LLD_CHECK_EQ(late_fee_cents(children, 10), 0), and it pins that reasoning down, so a later change to the fee code cannot silently break it. The existing tests answer another question for free: does the change break anything else?

If “no fees” is an important rule, an explicit field such as bool charges_fees states it more clearly than a cap of 0, at the cost of one more thing for the code to check.

There is a catch: fee_per_day_cents must stay greater than 0, because the implementation divides by it. The header says so, but nothing checks it, and no test covers it. A children’s policy that set the daily fee to 0 instead of the cap would break that precondition, with undefined behaviour as the result. A requirement change is a good moment to re-read the preconditions, and to decide whether one this easy to break should be checked.

Exercise: Write the missing boundary tests

days_allowed(policy, renewals) returns how many days a member may keep an item after renewals renewals, counted from the day it was first borrowed: policy.loan_days * (renewals + 1). It has no tests yet.

  1. Which inputs would you test, and why each one?
  2. Write the test with the site’s harness.
Show the explained answer
  1. The inputs worth testing, with the default 21-day policy:

    • 0 renewals (never renewed): the smallest valid count, 21 days. A mistake such as loan_days * renewals would give 0.
    • 1 renewal: 42, the ordinary case, which shows the days add up.
    • 2 renewals, the renewal limit: 63, the largest count that can occur.
    • The smallest loan period, a one-day policy: 1 day. It checks that the result follows the policy, not a built-in 21.

    days_allowed does not check that renewals is within the limit; that is can_renew’s job. Deciding whether that is right is a design question worth raising, and the answer belongs in the header comment.

  2. These tests are part of the example and pass in every build:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_loan_rules.cpp
// days_allowed is loan_days * (renewals + 1): 21 * 1, 21 * 2, 21 * 3 with
// the default policy, and 1 * 1 for a one-day policy.
LLD_TEST(days_allowed_boundaries) {
const LoanPolicy policy; // 21-day loans
LLD_CHECK_EQ(days_allowed(policy, 0), 21); // never renewed
LLD_CHECK_EQ(days_allowed(policy, 1), 42);
LLD_CHECK_EQ(days_allowed(policy, 2), 63); // at the renewal limit
LoanPolicy one_day;
one_day.loan_days = 1;
LLD_CHECK_EQ(days_allowed(one_day, 0), 1); // smallest loan period
}
  • A unit test calls code directly and checks the result automatically, on every build.
  • Structure each test as arrange, act, assert, and name it after the behaviour it checks.
  • Test the boundaries (each limit, and just inside and outside it) and the failure paths (refusals and documented errors), not only ordinary values.
  • Register tests with CTest; choose them with -R (name) or -L (label), and read failures with --output-on-failure.
  • See each new test fail once, so you know it can.