Building a Test Harness

When you test a function by hand, you call it, look at the output and decide whether it is right. That stops working once the function needs a database, a network service or forty input combinations. The solution is to build scaffolding around the code so tests run the same way every time, without you in the loop. This lesson covers what that scaffolding contains, how to set up and tear down its state, and how to estimate what each design choice costs in run time.

What a harness contains

A test harness is the code and data that surround a unit under test so it can run automatically: it supplies inputs, prepares any required state, checks results and reports them. It can also replace dependencies. Testing frameworks provide ready-made harness pieces; the following are common components, chosen to suit the tests.


Block diagram with a test driver sending inputs to a unit under test, which calls a stub and receives state from a fixture, while the driver passes results to an oracle.


Component

Job

Example

Driver

Calls the unit under test with each test input

A loop over a list of cases

Stub

Replaces a dependency with fixed replies

A function that always returns a rate of 1.10

Mock object

Replaces a dependency and checks expected interactions

Confirms the email service was called once

Fixture

Builds known state before a test

A fresh in-memory copy of a database

Oracle

Decides whether the output is correct

An expected value, with a tolerance for floats

Reporter

Summarizes test outcomes

A pass count and failure details


Stubs and mocks are both test doubles. Doubles are needed only when a test replaces dependencies. Consider replacing a dependency when it is slow, costs money, needs a network or gives different answers on different days; uncontrolled live data can make a failure difficult to interpret.

Fixtures: setup, teardown and scope

A fixture is the known state a test starts from, together with the setup code that builds it and the teardown code that releases it. The rule that makes a harness trustworthy is that each test must start from its intended known state independently of previous tests.


The fixture's scope sets how often setup and teardown run. With nn tests, setup time ss, teardown time dd and test-body time bb:


Tper-test=n (s+b+d)Tshared=s+d+n bT_{\text{per-test}} = n\,(s + b + d) \qquad T_{\text{shared}} = s + d + n\,b


These estimates exclude reporting overhead and any additional resets; include reset time if sharing requires it.


Example: 30 tests with s=0.6s = 0.6 s, d=0.2d = 0.2 s and b=0.05b = 0.05 s take 30×0.85=25.530 \times 0.85 = 25.5 s with a per-test fixture, but only 0.8+30×0.05=2.30.8 + 30 \times 0.05 = 2.3 s when the fixture is shared without resets.


Scope

Setup runs

Isolation

Use when

Per test

Once per test

Fresh fixture state isolates tests if other relevant state is controlled

Tests modify the state

Shared (module or session)

Once per run

Preserved if relevant state remains unchanged or is reliably restored

Setup is expensive and state is read-only or cheap to reset



A minimal harness without a framework

Seeing the parts in plain code makes framework features easier to understand later. This driver tests an existing currency converter convert(amount, currency, rates):


Python
def fake_rates(currency):              # stub
    return {"EUR": 1.10, "GBP": 1.27}[currency]

def setup():                           # fixture setup
    return {"ledger": [], "rates": fake_rates}

def teardown(state):                   # fixture teardown
    state["ledger"].clear()

cases = [(100, "EUR", 110.0), (50, "GBP", 63.5)]

def run():                             # driver
    failures = 0
    errors = []
    for amount, cur, expected in cases:
        state = setup()
        try:
            actual = convert(amount, cur, state["rates"])
            if abs(actual - expected) > 1e-9:   # oracle
                failures += 1
        except Exception as error:
            failures += 1
            errors.append(f"{amount} {cur}: {error!r}")
        finally:
            teardown(state)
    for error in errors:
        print(error)
    print(f"{len(cases) - failures}/{len(cases)} passed")   # report


Each case gets fresh state, the stub removes the live rate service, and the tolerance check acts as the oracle. After successful setup, finally attempts teardown whether the test passes, fails or raises an exception. Unexpected test-body exceptions count as failures, are stored, and are reported after cleanup. A teardown exception propagates and stops this minimal driver.


A CI server needs a machine-readable outcome, such as a nonzero exit code on failure; this example only prints its report.



What to remember

  • Common harness components include a driver, fixtures, an oracle and a reporter; test doubles are used when replacing dependencies.
  • Each test needs its intended known state, independent of earlier tests.
  • Per-test fixtures cost n(s+b+d)n(s+b+d); shared fixtures cost s+d+nbs+d+nb, plus any reset overhead.
  • Sharing preserves isolation when relevant state is unchanged or reliably restored.
  • Use finally for teardown and define how unexpected exceptions affect reporting.

Example: Timing the harness for a fare calculator

You are building a harness for fare(distance_km, rider_type) in a transit app. The function reads prices from a tariff database and asks a live promotions service whether a discount applies. The test plan pairs each of 4 rider types (adult, student, senior, child) with each of 3 distances, one test case per pair. You measure these costs:

  • Loading a fresh in-memory copy of the tariff database (setup): 0.80 s
  • Discarding the copy (teardown): 0.20 s
  • One test body, with the promotions service stubbed: 0.05 s
  • One call to the live promotions service: 0.30 s, and each test body makes 2 calls

The fixture scope decides how often setup and teardown run: around every test, or once for the whole module.


a) If the harness called the live promotions service instead of a stub, how much extra time would it add to one full run? Assume the replaced stub calls take negligible time, the live calls run sequentially, and all other execution costs remain unchanged.


The driver runs one case per pairing of rider type and distance, so 4 × 3 gives ________. Each case makes 2 live calls, giving ________ in total. Under the stated timing assumptions, the extra time is the sum of the live-call durations.


extra time=24×0.30 s=7.2 s\text{extra time} = 24 \times 0.30\ \text{s} = 7.2\ \text{s}


The live service would add 7.2 s to every run. The stub also makes results repeatable: a live service could change a promotion overnight and break tests even though fare is unchanged.


b) With the stub in place and a per-test fixture, what is the total run time?


Each test pays for its own setup, body and teardown: 0.80 + 0.05 + 0.20 = ________ per test.


Tper-test=n (s+b+d)=12×1.05 s=12.6 sT_{\text{per-test}} = n\,(s + b + d) = 12 \times 1.05\ \text{s} = 12.6\ \text{s}


The run takes 12.6 s, and 12 × 1.00 = 12.0 s of that is fixture work rather than testing.


c) Switch to a module-scoped fixture that loads the tariff once. What is the new total run time, and how many times faster is it than the per-test design?


Setup and teardown now run once, costing 0.80 + 0.20 = ________. The twelve test bodies take 12 × 0.05 = ________.


Tshared=s+d+n b=1.00 s+0.60 s=1.60 sTper-testTshared=12.6 s1.60 s=7.875≈7.9\begin{aligned} T_{\text{shared}} &= s + d + n\,b = 1.00\ \text{s} + 0.60\ \text{s} = 1.60\ \text{s} \\ \frac{T_{\text{per-test}}}{T_{\text{shared}}} &= \frac{12.6\ \text{s}}{1.60\ \text{s}} = 7.875 \approx 7.9 \end{aligned}


The run takes 1.60 s, about 7.9 times faster than the per-test design.


d) One student-fare test applies a discount by writing to the tariff table. Explain the risk under the module-scoped fixture, then find the total run time if you add a reset step costing 0.02 s after every test.


With a shared tariff, the write persists unless it is reversed. Later tests accessing the modified tariff rows may observe discounted prices, making their results depend on test order rather than solely on whether fare is correct. Tests using unaffected rows need not be affected. Mutations must not affect subsequent tests; reliable restoration can preserve isolation. Restoring all changed rows after each test, even when a test fails, keeps the cheap one-time load while giving every test the same starting state.


The reset adds 12 × 0.02 = ________ to the run.


T=1.00 s+0.60 s+0.24 s=1.84 sT = 1.00\ \text{s} + 0.60\ \text{s} + 0.24\ \text{s} = 1.84\ \text{s}


The isolated, shared-fixture run takes 1.84 s, still about 12.6 / 1.84 ≈ 6.8 times faster than rebuilding the database for every test.

Match each component of a hand-built test harness with the role it plays when a single test case runs against the unit under test.

Match each term
A.

Code that calls the unit under test with prepared inputs and captures what it returns

B.

Step that releases resources and restores state once a test finishes

C.

Stand-in for a dependency that returns fixed, canned replies

D.

Known state or resources prepared before each test begins

E.

Stand-in dependency that also records its calls so the test can check them

F.

Rule or reference value that decides whether an observed output is correct

Mock object

Test oracle

Stub

Teardown

Fixture

Driver

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A hand-built harness runs one test case for a function that depends on an external currency service. This harness checks the function's result before performing cleanup. Put the events of that single test case in the order they occur.

  1. 1.

    Teardown discards the data copy and removes the stub.

  2. 2.

    The function under test calls the stub and receives its canned exchange rate.

  3. 3.

    Fixture setup builds a fresh data copy and installs a stub for the currency service.

  4. 4.

    The oracle compares the actual output with the expected value.

  5. 5.

    The driver calls the function under test with the test input.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A student's hand-built harness loads a list of user records once and shares it across every test in the module. Each test passes when run alone, but in the full run test_rename_user fails whenever test_delete_user runs before it. Which change fixes the cause of the failure?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice