TestingVol. 11 · Part XI
0 / 0

Shelves / Testing

TS·114

Testing Philosophy

Why we test and how much: confidence as the goal, the layers that produce it (types and static analysis, tests, reviews, observability, production controls), what a good test is, the test pyramid versus the trophy and honeycomb, testing behaviour rather than implementation, test sizes (small, medium, large), coverage and its limits, test-driven development, testing across paradigms (OOP, functional, systems languages), flaky tests, and test suites as a product that must stay fast.

22 topics · ~16 min read · 30-question quiz
Updated Suggest a correction

Start here: what testing is for, measured

Testing is not about proving code correct; that is almost never possible. It is about confidence: enough evidence, cheaply enough, that a change is safe to ship. So the useful questions are "what kinds of mistake can each kind of test catch?" and "what does each cost?"

The same behaviour at three levels

The tiffin bill was tested three ways: a unit test calling total(), an integration test that also saved the total to PostgreSQL and read it back (each test in a transaction that's rolled back), and an end-to-end (E2E) test that opened a web page in a real browser, typed a quantity, clicked Order and checked the confirmation:

Text
unit:         200 tests in 0.19 s   → about 1 ms per test
integration:   50 tests in 0.34 s   → about 7 ms per test (local PostgreSQL, rollback per test)
end-to-end:    10 tests in 5.56 s   → about 0.4–0.5 s per test (plus browser start-up)

An end-to-end test here cost about 500 times a unit test, and this was a one-page app on one machine; against real deployed services, E2E tests often take tens of seconds each. That cost is why you write many fast tests and a few slow ones.

But each level catches different bugs

The first E2E run failed every test:

Text
AssertionError: Locator expected to have text 'Order placed: ₹126.00'
Actual value: Order placed: ₹126.00

The page had no <meta charset="utf-8">, so the browser decoded the rupee sign's UTF-8 bytes as Windows-1252. The unit and integration tests passed, correctly: total() was right and the database stored the right number. Only a test that went through the real browser could see the bug the customer would see. Adding the meta tag fixed it. This is the case for having some tests at every level.

Flaky tests destroy trust

The page was changed to answer after a random 50–300 ms. Two ways of waiting for the confirmation, 40 runs each, run twice:

Text
sleep 0.2 s, then read the text:      17 of 40 failed, then 13 of 40 failed
auto-waiting assertion (expect):       0 of 40 failed, both times

A fixed sleep guesses how long the app will take; whenever it's slower, the test fails though nothing is wrong. That is a flaky test: it passes and fails with no code change. Playwright's expect(...).to_have_text(...) retries until the text appears (up to a timeout), so it waits exactly as long as needed. Small flake rates add up fast across a suite:

Text
chance a whole suite passes, with every test 0.1% flaky:
  100 tests: 90.5%   500: 60.6%   1,000: 36.8%   2,000: 13.5%   5,000: 0.7%
with 0.01% flaky:
  100 tests: 99.0%   500: 95.1%   1,000: 90.5%   2,000: 81.9%   5,000: 60.7%

Once a red build usually means "flaky, re-run it", people stop believing red builds, and real failures get re-run too.

How deep to go in testing philosophy

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 Explain why we test and name the test levels and their trade-offs
L2 Write tests at the right level for your own changes and keep them deterministic
L3 Explain the pyramid and its alternatives (trophy, honeycomb), coverage's limits and what makes a good test
L4 Diagnose a slow, flaky or low-value suite and fix it with measurements
L5 Design a test strategy for a system: levels, environments, data, CI gates and quality metrics
L6 Set testing standards and culture across an organisation and measure their effect

Confidence is the goal

Tests aren't the goal; confidence to change and ship software is. Confidence comes from several complementary sources, each catching different classes of mistakes at different costs:

confidence = tests + static checks + observability + reviews + production controls

static checkstypescompilerlinters · SAST testsunitintegrationcontract · E2E reviewsdesign docscode reviewpairing prod controlscanaryfeature flagsrollback observabilitymetricstraces · logsSLO alerts earlier, cheaper, narrower → later, costlier, more realistic production incidents become new tests
Layers of confidence from left (cheapest, earliest) to right (latest, closest to real users). Type systems and linters catch whole classes of errors before code runs; tests check behaviour; code review catches design and intent problems; production controls such as canaries and feature flags limit the blast radius of what slips through; observability detects what nobody predicted.

Implications:

  • Push checks left when they're cheap: a type system that makes invalid states unrepresentable removes tests you'd otherwise need (an enum instead of a string, Option<T> instead of null, a NonEmptyList).
  • Don't expect tests to catch everything: some failures only appear with real traffic, data and infrastructure. Progressive delivery (Vol. 6 ch. 84) and observability (Vol. 9) are part of your testing strategy.
  • Production incidents feed back into tests: every bug fixed gets a regression test at the lowest level that reproduces it.

What makes a good test

A test is worth having if it catches regressions and doesn't break for irrelevant reasons. Desirable properties (adapted from Kent Beck's "test desiderata"):

Property Meaning
Behavioural Fails when behaviour users care about changes
Structure-insensitive Doesn't fail when you refactor internals without changing behaviour
Deterministic Same result every run: no dependence on time, randomness, ordering, network
Fast Runs in milliseconds (unit) to seconds (integration), so developers run it constantly
Isolated Doesn't depend on or affect other tests; can run in any order and in parallel
Readable / specific Its name and failure message tell you what broke
Writable Cheap to write relative to the code under test
Predictive Passing means the code will work in production

These trade off against each other: a full end-to-end test is highly predictive but slow and less deterministic; a unit test with heavy mocking is fast but may be structure-sensitive and less predictive. Strategy is about choosing the mix.

Structure of a test

The Arrange–Act–Assert (or Given–When–Then) pattern keeps tests readable:

// Java (JUnit 6 + AssertJ)
@Test
void appliesTenPercentDiscountForGoldCustomers() {
    // Arrange
    var pricing = new Pricing(new DiscountPolicy());
    var customer = Customer.gold("ana");
    // Act
    Money total = pricing.total(customer, List.of(Money.eur(100), Money.eur(50)));
    // Assert
    assertThat(total).isEqualTo(Money.eur(135));
}

One behaviour per test, named after the behaviour (appliesTenPercentDiscountForGoldCustomers, not testTotal2).

Test levels and shapes

Sizes, not just names

"Unit" and "integration" mean different things to different teams. Google's test sizes classify tests by the resources they may use, which is what determines speed and reliability:

Size Constraints Typical examples
Small Single process (often single thread), no network, no disk, no sleep Pure functions, domain logic, in-memory fakes
Medium Single machine; localhost network, real databases in containers, file system Repository tests against Postgres in a container, HTTP handler tests with a real server on localhost
Large Multiple machines, real external systems End-to-end tests in a deployed environment, load tests

The pyramid, the trophy and the honeycomb

pyramid E2E integration unit (most) trophy E2E integration (most) unit static honeycomb integrated integration(service, real I/O) impl detail same principle: most tests where cost ÷ confidence is best for your architecture
Three popular shapes for a test portfolio. The pyramid (Mike Cohn) puts most tests at the fast unit level; the trophy (Kent C. Dodds, for front ends) emphasises integration tests on a base of static checks; the honeycomb (Spotify, for microservices) emphasises integration tests of each service through its real boundaries, with few implementation-detail unit tests and few cross-service E2E tests.
  • Test pyramid (Mike Cohn): many fast unit tests, fewer integration tests, very few end-to-end tests. Great for logic-heavy systems.
  • Testing trophy (Kent C. Dodds): static analysis as the base, then most effort on integration tests ("write tests, not too many, mostly integration"), because in UI code the value is in components working together.
  • Testing honeycomb (Spotify): for microservices that are mostly I/O glue, test each service through its real boundaries (HTTP in, real database via containers), with few implementation-detail tests.

The shapes disagree on emphasis but agree on the principle: put most of your effort where tests give the most confidence per unit of cost for your architecture, and keep slow, flaky, broad tests few.

Test behaviour, not implementation

The most common reason test suites become a burden is that they're coupled to implementation: they assert which private methods were called, mock every collaborator, or snapshot internal data structures. Then every refactor breaks dozens of tests even though behaviour didn't change, and developers stop trusting (or start deleting) tests.

Guidelines:

  • Test through public interfaces (a module's API, an HTTP endpoint, a component's rendered output), not private methods. If a private method is complex enough to need its own tests, it probably wants to be its own module.
  • Mock at architectural boundaries you own (ports such as PaymentGateway, Clock), not internal collaborators; prefer fakes and real objects where cheap (chapter 115).
  • Assert outcomes (returned values, state, emitted events, HTTP responses), not interactions, unless the interaction is the behaviour (e.g. "an email is sent").
  • Classicist (Detroit) vs mockist (London) TDD: classicists use real collaborators and mock only awkward ones; mockists mock all collaborators to design interactions. Most teams today lean classicist for domain logic.

Coverage

Code coverage measures which lines/branches the tests execute. Tools: JaCoCo (Java), go test -cover, coverage.py/pytest-cov, cargo llvm-cov, V8/Istanbul via Vitest/Jest, gcov/llvm-cov (C/C++).

  • Useful as a negative signal: uncovered code is definitely untested; coverage diffs on pull requests highlight new untested code.
  • Misleading as a target: 100% coverage says nothing about whether assertions are meaningful (a test with no assertions covers code). Goodhart's law: "when a measure becomes a target, it ceases to be a good measure".
  • Branch coverage is stronger than line coverage; mutation testing (chapter 115) measures whether tests actually detect changes.
  • Reasonable practice: track coverage, review uncovered critical paths, avoid hard global targets (or set a modest floor), and require tests for changed logic in reviews.

Test-driven development

TDD (Kent Beck): write a failing test, write the simplest code to pass, refactor; repeat in small steps (red → green → refactor).

Benefits: forces testable design and clear interfaces, keeps code covered, gives frequent feedback, and documents behaviour. Costs: discipline, and it's less natural for exploratory or UI-heavy work. Variants: outside-in (start from an acceptance test, drive inward), BDD (behaviour described in domain language, sometimes with Gherkin Given/When/Then files via Cucumber, though many teams find plain-code tests with good names enough).

Even without strict TDD, writing the test before fixing a bug (reproduce, see it fail, then fix) is universally valuable.

Testing across paradigms and languages

Style Testing implications
Object-oriented (Java, C#, Kotlin) Dependency injection makes collaborators replaceable; rich mocking frameworks (Mockito, MockK); beware over-mocking
Functional (Haskell, Elixir, Clojure, F#, functional cores in any language) Pure functions are trivially testable (input → output); property-based testing originated here (QuickCheck); push effects to the edges ("functional core, imperative shell")
Go Small interfaces defined by the consumer make fakes easy; table-driven tests; testing package built in; minimal mocking culture
Rust Tests in the same file (#[cfg(test)] mod tests) can test private items; integration tests in tests/; doc tests run code examples; traits for seams; strong types remove many tests
Python / JavaScript (dynamic) More tests needed for type-level mistakes unless using type checkers (mypy/pyright, TypeScript); monkeypatching makes mocking easy, and dangerously so
C No built-in framework (Unity, CMocka, Check, Criterion, GoogleTest from C++); seams via function pointers or link-time substitution; sanitizers (ASan, UBSan) and fuzzing are essential complements
Zig test blocks built in (zig build test); std.testing.allocator detects memory leaks in tests automatically

Haskell, for example, makes the pure core almost free to test:

Haskell
-- QuickCheck: a property, checked against 100 random inputs by default
import Test.QuickCheck
prop_reverseInvolutive :: [Int] -> Bool
prop_reverseInvolutive xs = reverse (reverse xs) == xs
-- ghci> quickCheck prop_reverseInvolutive   →   +++ OK, passed 100 tests.

Keeping the suite healthy

A test suite is a product used by every developer many times a day:

  • Speed: keep the inner loop (tests for the module you're changing) in seconds; parallelise; run only affected tests (Bazel, Nx, Gradle build cache, go test caching, pytest-xdist, test impact analysis).
  • Flakiness (tests that pass and fail without code changes) destroys trust: track flake rates, quarantine flaky tests with owners and deadlines, fix root causes (time, ordering, concurrency, shared state, network), and don't paper over with blind retries (chapter 118).
  • Clear failures: good assertion messages, diff-friendly assertions (AssertJ, pytest's assertion rewriting, pretty_assertions), logs and artifacts attached in CI.
  • Ownership: tests are code; review them, refactor them, delete tests that no longer give value.
  • CI gates: fast tests on every push, broader suites before merge, slow/large tests on a schedule or pre-release (Vol. 8 ch. 93).

Lab: the cost and value of each test level

pytest 9.1.1, psycopg 3.3 against PostgreSQL 16 on a Unix socket, and Playwright 1.63 (sync API) driving headless Chromium, all on the lab machine. The system under test is the Start Here chapter's total() and a one-page order form served by Python's http.server.

Experiment 1: the price of each level

Text
unit         200 passed in 0.19s
integration   50 passed in 0.34s      (module-scoped connection, rollback after each test)
end-to-end    10 passed in 5.56s      (--durations: setup 0.44 s, calls 0.42–0.44 s each)

The integration fixture pattern that made it fast:

Python
@pytest.fixture(scope="module")
def conn():
    c = psycopg.connect("host=/tmp port=5433 dbname=shop user=app")
    yield c; c.close()

@pytest.fixture
def tx(conn):
    yield conn
    conn.rollback()          # every test starts from the same clean state

Opening one connection per module and rolling back after each test keeps integration tests within a few times the cost of unit tests, which is why many teams now write more of them than the classic pyramid suggests (the "testing trophy"). The E2E cost is dominated by the browser: launching it is 0.44 s, and each journey costs about as much again; on a real deployed stack with network hops and real data, 10–60 s per journey is common.

Experiment 2: a bug only the top level can see

Text
first E2E run: 10 failed
  Expected: 'Order placed: ₹126.00'
  Actual:   'Order placed: ₹126.00'
after adding <meta charset="utf-8">: 10 passed

₹ is three bytes in UTF-8 (E2 82 B9). Without a declared charset, Chromium fell back to Windows-1252 and showed each byte as a character. This class of bug, where every unit is right and the assembly is wrong (encodings, configuration, wiring, CSS hiding a button, a proxy stripping a header), is what integration and E2E tests exist for.

Experiment 3: manufacturing and curing a flaky test

The page answers after 50 + Math.random() * 250 ms.

Text
run 1: sleep(0.2) then read: 17/40 failed    auto-wait expect: 0/40 failed
run 2: sleep(0.2) then read: 13/40 failed    auto-wait expect: 0/40 failed
expected failure rate for sleep(0.2): P(delay > 200 ms) = 100/250 = 40%

The observed 33–42% matches the model, which is the point: flakiness is usually a race between the test and the system, not bad luck. Other common causes, each with its fix: shared state between tests (isolate data per test), test order dependence (run in random order with pytest-randomly), real clocks and time zones (inject a clock), random seeds (log and fix them), external services (fake them at unit level, pin them at integration level), and resource limits in CI (measure, don't guess).

Experiment 4: what flakiness does at scale

Text
P(suite green) = (1 − p)^N
p = 0.1%:  N=100 → 90.5%   500 → 60.6%   1,000 → 36.8%   2,000 → 13.5%   5,000 → 0.7%
p = 0.01%: N=100 → 99.0%   500 → 95.1%   1,000 → 90.5%   2,000 → 81.9%   5,000 → 60.7%

Large organisations report flaky failures as a substantial share of all CI failures, and respond with tooling: automatic reruns that record flakes, quarantine for tests above a flake threshold with an owner and a deadline, and dashboards of the flakiest tests. Retrying silently hides the problem; quarantining with an owner fixes it.

Try it yourself

  1. Change the integration fixture to open a new connection per test and measure the difference.
  2. Install pytest-randomly and run your own project's suite three times. Does anything fail only in some orders?
  3. Add a test that reads datetime.now() and fails at midnight. Then fix it by injecting a clock.
  4. Measure your team's suite: count tests by level and time per level, and compare the shape with a pyramid.

Revision sheet: testing philosophy

Key ideas

  • Goal: justified confidence that a change is safe, at acceptable cost; tests are one layer among types, static analysis, review, observability and progressive delivery.
  • Levels: unit, integration, contract, E2E, performance, chaos; lower is faster and more precise, higher is broader and slower.
  • Shapes: the pyramid (many unit, few E2E), the trophy (integration-heavy, static analysis at the base), the honeycomb (for microservices, mostly integration and contract); choose by where your bugs actually come from.
  • A good test is fast, deterministic, isolated, readable, tests behaviour not implementation, and fails for one clear reason.
  • Coverage shows what was executed, not what was checked; use it to find untested code, not as a target.
  • Flakiness is usually a race, shared state, time or environment; quarantine with an owner, never ignore.
  • Shift left and right: test early in development and verify in production (canaries, synthetic checks, SLOs).

Numbers to remember

  • Lab: unit ≈ 1 ms, integration ≈ 7 ms, E2E ≈ 0.4–0.5 s per test (≈500× a unit test).
  • Lab: a 0.2 s sleep against a 50–300 ms response failed 33–42% of runs; auto-waiting failed 0%.
  • 1,000 tests at 0.1% flakiness: suite green only 36.8% of the time.

Pitfalls

  • Coverage targets that reward tests without assertions.
  • Testing implementation details, so refactors break tests that should pass.
  • Fixed sleeps in UI and async tests.
  • One giant E2E suite as the main safety net.
  • Tests sharing data or depending on order.
  • Retrying failures silently instead of tracking flakes.

Glossary

  • Test pyramid / trophy / honeycomb: models of how many tests to have at each level.
  • System under test (SUT): what a test exercises.
  • Deterministic: same inputs, same result, every run.
  • Quarantine: running a known-flaky test outside the gating suite until fixed.
  • Shift left: catching problems earlier in the development cycle.