TestingVol. 11 · Part XI
0 / 0

Shelves / Testing

TS·115

Unit Testing

Fast, isolated, deterministic tests of units of behaviour: what a unit is, frameworks in each language (JUnit 6, go test, pytest, cargo test, Vitest, Unity/CMocka for C, Zig test blocks), table-driven and parameterised tests, fixtures and setup, controlling time and randomness, test doubles (dummies, stubs, spies, mocks, fakes) and when to use each, designing seams with dependency injection, testing errors and concurrency, snapshot tests, property-based testing (QuickCheck, Hypothesis, jqwik, proptest, fast-check, Go fuzzing), and mutation testing (PIT, Stryker, cargo-mutants, mutmut).

27 topics · ~25 min read · 31-question quiz
Updated Suggest a correction

Start here: unit tests that can actually fail

A unit test checks one small piece of behaviour, fast and in isolation, so that when it fails you know exactly what broke. The hard part isn't writing tests that pass; it's writing tests that would fail if the code were wrong.

100% coverage, and still almost no protection

The delivery fee: free from ₹500; otherwise ₹20 plus ₹8 per km beyond 2 km, capped at ₹80.

Python
def delivery_fee(distance_km, subtotal):
    if subtotal >= 500:
        return 0
    fee = 20
    if distance_km > 2:
        fee += 8 * (distance_km - 2)
    return min(fee, 80)

A weak test calls it four times (every line and branch runs) and asserts only that one fee is positive:

Text
coverage: 11 statements, 4 branches, 100%
mutation testing: 18 mutants, 6 killed, 12 survived

Mutation testing (mutmut) makes small deliberate bugs in the code, one at a time, and runs the tests against each. A mutant the tests catch is "killed"; one they don't notice "survived". Some survivors:

Text
-    if subtotal >= 500:          +    if subtotal > 500:
-        return 0                 +        return 1
-        fee += 8 * (distance_km - 2)   +        fee = 8 * (distance_km - 2)
-    return min(fee, 80)          +    return min(fee, 81)

Each is a believable real bug, and the "100% covered" suite passed with all of them. Coverage tells you code ran; only assertions tell you it was checked.

Boundary values kill mutants

A table of cases at and around every edge in the rules:

Python
@pytest.mark.parametrize("km, subtotal, fee", [
    (1, 100, 20), (2, 100, 20), (3, 100, 28), (5, 100, 44), (9, 100, 76),
    (10, 100, 80), (20, 100, 80), (5, 499, 44), (5, 500, 0), (5, 900, 0),
])
def test_delivery_fee(km, subtotal, fee):
    assert delivery_fee(km, subtotal) == fee
Text
mutation testing: 18 mutants, 17 killed, 1 survived
survivor:  -    if distance_km > 2:   +    if distance_km >= 2:

The last survivor is an equivalent mutant: at exactly 2 km both versions add 8 × 0, so no test can tell them apart. The suite is as strong as this code allows.

Tests that depend on the clock

Python
def is_open(now=None):                       # kitchen open 07:00–22:00
    now = now or datetime.now()
    return time(7, 0) <= now.time() < time(22, 0)

One test calls is_open() with the real clock; the others pass fixed times. The same suite run under different time zones:

Text
UTC                  10:47  7 passed
Asia/Kolkata         16:17  7 passed
Pacific/Auckland     23:47  1 failed, 6 passed
America/Los_Angeles  03:47  1 failed, 6 passed

The clock-dependent test is correct by day and fails by night. Passing now in (injecting the dependency) makes every case deterministic, including the edges 06:59, 07:00, 21:59 and 22:00.

Tests that pass by luck: a data race

A Go order counter incremented by 100 goroutines × 100 times, with and without a mutex:

Text
go test (20 runs of the unsafe counter):  10 pass, 10 fail   e.g. "got 9576 orders, want 10000"
go test -race:                            WARNING: DATA RACE … counter.go:6
                                          race detected during execution of test → FAIL

Without the race detector the test failed only half the time; with -race it failed every time and pointed at the line. Concurrency bugs need tools that make them deterministic.

How deep to go in unit testing

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Write a simple arrange-act-assert test in your language's framework
L2 Write table-driven, boundary-value and property tests with fixtures and test doubles
L3 Explain test doubles (stub, fake, mock, spy), dependency injection, property shrinking and mutation testing
L4 Find weak, flaky or racy unit tests and strengthen them using mutation testing and race detectors
L5 Design code for testability and set unit-testing conventions for a codebase
L6 Set unit-testing standards and quality signals across an organisation

What is a unit?

A unit test exercises a small piece of behaviour in isolation from slow or non-deterministic dependencies (network, databases, clocks, file systems). "Unit" means a unit of behaviour, not necessarily one class or function:

  • Solitary unit tests isolate a single class/function, replacing its collaborators with doubles.
  • Sociable unit tests let the unit use its real in-process collaborators (domain objects, pure helpers) and replace only the awkward ones (I/O, time).

Sociable tests are usually more refactoring-friendly. What matters is that unit tests are fast (milliseconds), deterministic, and isolated from each other.

Frameworks by language

Language Framework(s) Notes
Java/Kotlin JUnit 6 (Jupiter API; Java 17+; unified versioning; Kotlin suspend tests), AssertJ, Mockito, jqwik, Kotest/MockK for Kotlin @Test, @ParameterizedTest, @Nested, extensions
Go testing (built in), testify (assert/require), go-cmp go test ./..., table-driven tests, t.Run subtests, t.Parallel(), built-in fuzzing, testing/synctest for time/concurrency
Python pytest (de facto), unittest (stdlib), Hypothesis Fixtures via dependency injection, parametrize, plain assert with rich diffs
Rust Built-in #[test], cargo test (or cargo nextest), proptest, mockall, insta Unit tests in the module (#[cfg(test)]), integration tests in tests/, doc tests
TypeScript/JS Vitest, Jest, Node's built-in node:test Vitest is Vite-native and fast; fake timers; module mocking
C Unity, CMocka, Criterion, Check, GoogleTest Combine with sanitizers and fuzzing
Zig Built-in test "name" { … } std.testing.expectEqual, leak-detecting allocator
C# xUnit, NUnit, MSTest Moq/NSubstitute
Haskell/Elixir Hspec + QuickCheck; ExUnit + StreamData Property testing native to the culture

Writing unit tests

Table-driven and parameterised tests

When one behaviour has many input/output cases, express them as data:

// Go: table-driven test with subtests
func TestParseDuration(t *testing.T) {
    tests := []struct {
        name    string
        in      string
        want    time.Duration
        wantErr bool
    }{
        {"seconds", "30s", 30 * time.Second, false},
        {"minutes", "5m", 5 * time.Minute, false},
        {"compound", "1h30m", 90 * time.Minute, false},
        {"empty", "", 0, true},
        {"garbage", "abc", 0, true},
    }
    for _, tc := range tests {
        t.Run(tc.name, func(t *testing.T) {
            t.Parallel()
            got, err := ParseDuration(tc.in)
            if (err != nil) != tc.wantErr {
                t.Fatalf("err = %v, wantErr %v", err, tc.wantErr)
            }
            if got != tc.want {
                t.Errorf("got %v, want %v", got, tc.want)
            }
        })
    }
}

Fixtures and setup

Fixtures establish the known state a test needs. Keep them minimal and explicit: shared giant fixtures make tests hard to read ("mystery guest") and couple tests to each other.

  • Builders / object mothers: anOrder().withItems(2).paid().build() produce valid objects with sensible defaults; tests override only what they care about.
  • Framework fixtures: JUnit @BeforeEach/extensions, pytest fixtures (dependency-injected by parameter name, scoped per function/module/session, with yield teardown), Go helper functions with t.Helper() and t.Cleanup(), Rust helper functions or rstest fixtures, Vitest beforeEach and test context.
  • Fresh state per test: never rely on the previous test's leftovers; that breaks parallelism and ordering.
Python
# pytest fixtures: composed by name, with teardown after yield
import pytest

@pytest.fixture
def clock():
    return FakeClock(datetime(2026, 1, 1, tzinfo=UTC))

@pytest.fixture
def repo():
    r = InMemoryOrderRepo()
    yield r
    r.clear()                          # teardown

def test_order_expires_after_30_minutes(clock, repo):
    svc = OrderService(repo, clock)
    order = svc.place(items=[Item("book", 1)])
    clock.advance(minutes=31)
    assert svc.status(order.id) == "expired"
Go
// Go helper with cleanup
func newTestStore(t *testing.T) *Store {
    t.Helper()
    dir := t.TempDir()                 // removed automatically after the test
    s, err := OpenStore(filepath.Join(dir, "db"))
    if err != nil { t.Fatal(err) }
    t.Cleanup(func() { s.Close() })
    return s
}

Determinism

Non-deterministic tests are flaky tests. Usual sources and their fixes:

Source Fix
Current time Inject a clock (java.time.Clock, a Clock interface in Go, time-machine/freezegun in Python, Vitest vi.useFakeTimers(), a Clock trait in Rust)
Randomness Inject the RNG or seed it; log the seed on failure
Concurrency/scheduling Avoid sleep-based waits; use synchronisation, deterministic schedulers (Go testing/synctest, Tokio's paused time #[tokio::test(start_paused = true)], Kotlin runTest virtual time), or loom for Rust concurrency models
Ordering Don't depend on map/set iteration order or test execution order; sort before comparing
Environment Locale, time zone, file system paths, environment variables: set explicitly
Network/I/O Not in unit tests; replace with fakes
Floating point Compare with tolerances
// Java: inject java.time.Clock
class TokenService {
    private final Clock clock;
    TokenService(Clock clock) { this.clock = clock; }
    boolean isExpired(Token t) { return Instant.now(clock).isAfter(t.expiresAt()); }
}

@Test
void tokenExpiresAfterDeadline() {
    var clock = Clock.fixed(Instant.parse("2026-10-24T10:00:00Z"), ZoneOffset.UTC);
    var svc = new TokenService(clock);
    assertThat(svc.isExpired(new Token(Instant.parse("2026-10-24T09:59:59Z")))).isTrue();
}

Test doubles

Test double (Gerard Meszaros) is the umbrella term for objects that stand in for real dependencies:

Double What it does Example
Dummy Passed but never used A null logger to satisfy a constructor
Stub Returns canned answers to calls rates.get("EUR") returns 1.1
Spy A stub that also records how it was called, for later assertions Records emails "sent"
Mock Pre-programmed with expectations; verifies the interactions verify(gateway).charge(amount)
Fake A working, simplified implementation In-memory repository, fake clock, local SMTP stub
dummyfills a slot stubcanned answers spyrecords calls mockverifies calls fakereal, simplified more behaviour queries → stub/fake · commands → spy/mock · prefer fakes
Test doubles from least to most behaviour. Dummies fill parameters; stubs return canned answers (state verification); spies record calls; mocks verify expected interactions (behaviour verification); fakes are lightweight working implementations. Prefer real objects and fakes where cheap, stubs for queries, and mocks only for commands whose call is the behaviour under test.

Queries versus commands

  • For queries (calls that return data, no side effects), use stubs or fakes and assert on the result of the unit under test. Verifying that a query was called couples the test to implementation.
  • For commands (calls whose purpose is a side effect: send email, publish event, charge card), the call is the observable behaviour, so verify it with a spy or mock, or use a fake that records outcomes.
// Java: Mockito stub for a query, verify for a command
@ExtendWith(MockitoExtension.class)
class CheckoutTest {
    @Mock ExchangeRates rates;          // query
    @Mock PaymentGateway gateway;       // command

    @Test
    void chargesConvertedAmount() {
        when(rates.rate("USD", "EUR")).thenReturn(new BigDecimal("0.90"));
        var checkout = new Checkout(rates, gateway);

        checkout.pay(Money.usd(100), "EUR");

        verify(gateway).charge(Money.eur(90));          // the side effect is the behaviour
        verifyNoMoreInteractions(gateway);
    }
}

Mocking pitfalls

  • Over-mocking: every collaborator mocked, tests mirror the implementation line by line. Refactoring becomes painful and tests pass even when the system is broken.
  • Mocking types you don't own (an HTTP client library, an AWS SDK): your mock encodes your assumptions about the library, which may be wrong. Wrap the third-party API behind your own interface (an adapter), mock that in unit tests, and test the adapter against the real thing (or a high-fidelity fake such as LocalStack or WireMock) in integration tests (chapter 116).
  • Drift: fakes and mocks diverge from reality over time. Run the same contract test suite against both the fake and the real implementation to keep them honest.
  • Global monkeypatching (Python patch("module.thing"), Jest module mocks) is convenient but couples tests to import paths; prefer dependency injection.

Seams and dependency injection

A seam is a place where behaviour can be substituted without editing the code under test (Michael Feathers). Create seams by passing dependencies in rather than constructing them inside:

  • OOP: constructor injection of interfaces (manually or with Spring/Guice/Dagger).
  • Go: accept small interfaces, return structs; define the interface where it's used.
  • Rust: generic parameters with trait bounds (fn new<G: Gateway>(g: G)) or trait objects (Box<dyn Gateway>).
  • Functional: pass functions as arguments; keep effects at the edges and test the pure core directly.
  • C: function pointers in structs, or link-time substitution (compile tests against a fake implementation of a header).

Testing errors, edge cases and concurrency

  • Test error paths as carefully as happy paths: invalid input, dependency failures (the stub returns an error), timeouts, partial failures. Many production incidents live in error-handling code that was never executed in tests.
  • Boundaries: empty, one, many; zero, negative, maximum; Unicode and very long strings; leap years, DST transitions and time zones.
  • Concurrency: run tests with the race detector (go test -race, ThreadSanitizer for C/C++/Rust), stress-repeat suspicious tests (go test -race -count=1000 -run TestX; retrying until green hides the bug instead), and use model checkers (loom in Rust, jcstress for Java memory-model behaviour).
  • Memory errors in C/C++/Zig/unsafe Rust: run unit tests under AddressSanitizer/UBSan/Valgrind or Miri (cargo +nightly miri test), and Zig's debug safety checks and testing allocator.

Snapshot (golden) tests

Snapshot tests record the output (rendered HTML, JSON, CLI text, generated code) to a file and fail when it changes: Jest/Vitest toMatchSnapshot, insta (Rust), syrupy (Python), Go golden files with an -update flag, ApprovalTests (Java and others).

They're cheap to write and good for large structured outputs, but dangerous when snapshots are huge and reviewers blindly accept updates. Keep snapshots small and reviewed, prefer inline snapshots for short outputs, and don't use them as the only test of logic.

Property-based testing

The idea

Example-based tests check the cases you thought of. Property-based testing (PBT) states properties that should hold for all inputs, generates hundreds of random inputs (including nasty edge cases), and when a property fails, shrinks the input to a minimal counterexample.

Pioneered by QuickCheck (Haskell, 2000). Implementations: Hypothesis (Python), jqwik (Java), proptest/quickcheck (Rust), fast-check (TypeScript), rapid and testing/quick (Go), StreamData (Elixir), RapidCheck (C++).

Finding properties

Pattern Example
Round trip decode(encode(x)) == x (serialisers, parsers, compression)
Invariants Sorting keeps the same elements and length; output is ordered; balance never negative
Idempotence normalise(normalise(x)) == normalise(x)
Oracle / reference model Optimised implementation agrees with a simple, obviously correct one
Commutativity / algebraic laws Merging CRDT states in any order gives the same result
Metamorphic Adding a filter can only shrink search results
Stateful / model-based Random sequences of operations on the system match a simple model (a queue vs a list)
# Hypothesis: round-trip and invariants, with automatic shrinking
from hypothesis import given, strategies as st

@given(st.lists(st.integers()))
def test_sort_properties(xs):
    out = my_sort(xs)
    assert len(out) == len(xs)
    assert sorted(out) == out                 # ordered
    assert Counter(out) == Counter(xs)        # same elements

@given(st.dictionaries(st.text(), st.integers()))
def test_json_round_trip(d):
    assert decode(encode(d)) == d

When a property fails, Hypothesis might report: Falsifying example: test_json_round_trip(d={'\x00': 0}): a minimal case you'd never have written. Failing examples are saved and replayed on the next run.

Fuzzing is closely related: coverage-guided fuzzers (libFuzzer, AFL++, Go's native fuzzing, cargo-fuzz, Jazzer, Atheris) mutate inputs to explore new code paths, looking for crashes, panics, sanitizer errors and assertion failures. It's essential for parsers and anything handling untrusted input, especially in C/C++.

Mutation testing

How do you know your tests would catch a bug? Mutation testing deliberately introduces small bugs (mutants) into the code and runs the tests:

  • Mutation operators: change < to <=, + to -, true to false, remove a method call, return a default value.
  • If a test fails, the mutant is killed (good). If all tests pass, the mutant survived: your tests don't check that behaviour.
  • Mutation score = killed / total (excluding equivalent mutants that don't change behaviour).
Java
// Code under test
boolean isAdult(int age) { return age >= 18; }

// Test suite
@Test void adult() { assertThat(isAdult(30)).isTrue(); }
@Test void child() { assertThat(isAdult(5)).isFalse(); }

// Mutant: "age > 18" — both tests still pass → SURVIVED.
// Coverage is 100%, but the boundary isn't tested. Add:
@Test void exactlyEighteenIsAdult() { assertThat(isAdult(18)).isTrue(); }   // kills the mutant

Tools: PIT (Java, Maven/Gradle plugins), Stryker (JavaScript/TypeScript, C#, Scala), cargo-mutants (Rust), mutmut/cosmic-ray (Python), go-mutesting/gremlins (Go), Mull (C/C++). Mutation testing is CPU-heavy: run it on changed code in pull requests or nightly on critical modules, and use surviving mutants as prompts for missing tests rather than chasing a perfect score.

Lab: strong unit tests, measured

pytest 9.1.1, coverage 7.17 with branch coverage, mutmut 3.8.1, and Go 1.24.7 with the race detector, on the lab machine.

Experiment 1: coverage versus mutation score

TOML
[tool.mutmut]
source_paths = ["src/"]
pythonpath = ["src"]
Suite Line+branch coverage Mutants Killed Survived
weak (4 calls, 1 assertion) 100% 18 6 12
boundary table (10 cases) 100% 18 17 1 (equivalent)

mutmut run took about one second (≈17–18 mutants per second for this tiny module); mutmut results lists survivors and mutmut show <id> prints the diff. Mutation testing is expensive on large codebases because each mutant reruns tests, so run it on changed files in CI or nightly, and read the survivors: each one is either a missing test or an equivalent mutant to mark as such. The same technique exists for other languages: PIT for Java, Stryker for JavaScript and TypeScript, for Rust with cargo-mutants, for Go with go-mutesting or gremlins.

Experiment 2: the clock as a hidden input

Text
TZ=UTC                  10:47  7 passed
TZ=Asia/Kolkata         16:17  7 passed
TZ=Pacific/Auckland     23:47  1 failed, 6 passed
TZ=America/Los_Angeles  03:47  1 failed, 6 passed

Hidden inputs make tests nondeterministic: the clock, the time zone, the locale, random numbers, environment variables, the file system, the network and global state. The cure is the same each time: make the input explicit (a parameter, a Clock interface in Java's java.time.Clock, time.Now injected as a function in Go, freezegun or time-machine in Python only as a last resort), then test the boundaries with fixed values. Running a suite under an unusual TZ and locale in CI is a cheap way to flush these out.

Experiment 3: the race detector

Go
type Orders struct{ n int }
func (o *Orders) Add() { o.n++ }          // read, add, write: three steps, no lock
Text
plain go test, 20 runs:   10 pass, 10 fail   ("got 9576 orders, want 10000")
go test -race:            WARNING: DATA RACE at counter.go:6 (read and write by different goroutines)
                          race detected during execution of test → FAIL every run
mutex version:            passes with and without -race

o.n++ compiles to a load, an add and a store; two goroutines can load the same value and one increment is lost. The detector (ThreadSanitizer underneath) records memory accesses and the happens-before relation between goroutines, so it reports the race even on runs where no update happened to be lost. It slows tests 2–20× and uses more memory, so CI usually runs a -race job alongside the fast one. Java has no built-in equivalent; use jcstress for concurrency tests and tools like the IntelliJ or Infer analysers.

Experiment 4: which double to use

The billing tests (Start Here) needed no doubles at all: pure functions are the easiest code to test. When a unit talks to something slow or external, choose the lightest double that works:

Double What it does Use when
Stub returns canned answers you need a dependency to answer, and don't care how it was called
Fake a working lightweight version (in-memory repository) many tests need realistic behaviour
Mock records calls and asserts on them the call itself is the behaviour (an SMS was sent once)
Spy wraps the real thing and records calls you want real behaviour plus a check

Over-mocking makes tests mirror the implementation: rename an internal method and dozens of tests fail though nothing user-visible changed. Prefer asserting on outputs and state, and use mocks for genuine side effects at the boundary.

Try it yourself

  1. Add a new rule (₹10 surcharge after 21:00) to delivery_fee with the clock injected, and get the mutation score back to "only equivalents survive".
  2. Run mutmut on a real module of yours and classify the first ten survivors.
  3. Replace the mutex in the Go counter with sync/atomic and benchmark both with go test -bench . -race and without.
  4. Write a Hypothesis property for delivery_fee: the fee never decreases as distance grows (for a fixed subtotal below ₹500). Does it find anything?

Revision sheet: unit testing

Key ideas

  • A unit is a unit of behaviour, not necessarily one class or function; test through its public interface.
  • FIRST: fast, isolated, repeatable, self-validating, timely.
  • Arrange-act-assert; one reason to fail; names that read as behaviour.
  • Table-driven / parametrised tests for many cases; boundary values at every rule edge.
  • Property-based tests (Hypothesis, jqwik, fast-check, proptest, rapid) for invariants, round-trips and model comparisons; shrinking gives minimal failures.
  • Test doubles: stub, fake, mock, spy; prefer fakes and state checks; mock only real side effects.
  • Hidden inputs (clock, TZ, randomness, env, global state) make tests flaky; inject them.
  • Coverage finds untested code; mutation testing measures whether tests check behaviour.
  • Concurrency: race detectors (go test -race, TSan), stress and jcstress-style tests.

Numbers to remember

  • Lab: weak suite 100% coverage but 6/18 mutants killed; boundary suite 17/18 (one equivalent).
  • Lab: racy counter failed 10/20 plain runs, 100% under -race; one lost-update run counted 9,576 of 10,000.
  • A healthy unit test runs in about a millisecond; a whole unit suite should run in seconds.

Pitfalls

  • Assertion-free or assert-something tests chasing coverage.
  • Mocking everything, so tests break on refactors and miss real bugs.
  • Testing private methods directly instead of behaviour.
  • Real time, randomness or network in unit tests.
  • Shared mutable fixtures leaking state between tests.
  • Treating every surviving mutant as a missing test (some are equivalent).

Glossary

  • Mutant / killed / survived: a deliberately bugged copy / detected by tests / not detected.
  • Equivalent mutant: a change that doesn't alter behaviour.
  • Fixture: reusable setup (pytest fixture, JUnit @BeforeEach).
  • Dependency injection: passing collaborators in so tests can substitute them.
  • Data race: unsynchronised concurrent access where at least one is a write.