Software Testing
Testing that gives confidence — the test pyramid and trophy, unit, integration, contract and end-to-end tests, writing good tests (AAA, one behaviour each), test doubles (mocks, stubs, fakes), TDD, property-based and mutation testing, coverage, flaky tests, and testing in production.
Tests let you change code without fear. A good suite catches regressions in seconds, documents behaviour, and makes refactoring, upgrades and continuous deployment possible (CI/CD). A bad suite is slow, flaky and breaks on every harmless refactor.
Levels of testing
| Level | Tests | Speed | Confidence | Example |
|---|---|---|---|---|
| Unit | One function or class in isolation | Milliseconds | That the logic is right | calculateDiscount returns 10% for gold members |
| Integration | Several components together, often with real infrastructure | Seconds | That the pieces fit | Repository code against a real PostgreSQL in a container |
| Contract | The agreement between a consumer and a provider | Fast | That services remain compatible | Pact tests between the web app and the orders API |
| End-to-end (E2E) | The whole system through its UI or API | Slow | That user journeys work | Playwright: sign up, add to cart, check out |
| Non-functional | Performance, load, security, accessibility | Varies | That it's fast, secure, usable | k6 load test; OWASP ZAP scan; axe checks |
The test pyramid
Many fast unit tests, fewer integration tests, and a handful of E2E tests. E2E tests are valuable but slow, brittle and hard to debug. The testing trophy variant (popular for front ends) emphasises integration tests — testing components the way users use them, with fewer mocks — because they give the most confidence per test. Either way: optimise for confidence per unit of maintenance cost.
Writing good tests
import pytest
from shop.pricing import price_order, Customer, Item
def test_gold_members_get_ten_percent_off_orders_over_1000():
# Arrange
customer = Customer(tier="gold")
items = [Item(sku="A", price=800, qty=2)]
# Act
total = price_order(customer, items)
# Assert
assert total == 1440 # 1600 - 10%
@pytest.mark.parametrize("tier, expected", [("standard", 1600), ("silver", 1520), ("gold", 1440)])
def test_discount_by_tier(tier, expected):
assert price_order(Customer(tier=tier), [Item("A", 800, 2)]) == expected
def test_rejects_negative_quantities():
with pytest.raises(ValueError, match="quantity"):
price_order(Customer(tier="standard"), [Item("A", 800, -1)])Principles:
- Arrange–Act–Assert (Given–When–Then) structure.
- One behaviour per test, with a name that states it — a failing test name should tell you what broke.
- Test behaviour, not implementation: assert on outputs and observable effects, not private methods or call order. Tests coupled to internals break on every refactor.
- Deterministic: no dependence on time, randomness, ordering or network — inject clocks and seeds.
- Independent: no shared mutable state; any order, in parallel.
- Fast: a unit suite should run in seconds so people run it constantly.
- Cover edge cases: empty, one, many; boundaries (0, −1, max); invalid input; errors; concurrency; time zones and Unicode.
- Tests are code: keep them readable; use helpers and builders for setup, but prefer clarity to DRY in assertions.
Test doubles
Replace real dependencies when they're slow, nondeterministic, or have side effects:
| Double | What it does | Example |
|---|---|---|
| Dummy | Fills a parameter; never used | None logger |
| Stub | Returns canned answers | Exchange-rate service always returns 83.2 |
| Fake | A working lightweight implementation | In-memory repository; SQLite instead of Postgres |
| Mock | Verifies interactions — expected calls | "Email service was called once with this address" |
| Spy | Records calls on a real object for later assertions | — |
// Vitest/Jest: stub a dependency injected through the constructor
test("sends a receipt after successful payment", async () => {
const payments = { charge: vi.fn().mockResolvedValue({ status: "succeeded" }) };
const mailer = { send: vi.fn() };
const checkout = new Checkout(payments, mailer);
await checkout.complete(order);
expect(mailer.send).toHaveBeenCalledWith(order.email, expect.stringContaining("Receipt"));
});Guidelines:
- Mock at boundaries you own (your
PaymentGatewayinterface), not third-party internals. - Prefer fakes and real infrastructure (Testcontainers) for databases — mocking SQL tests nothing about SQL.
- Over-mocking produces tests that pass while the real system is broken, and that break on refactors. Mock roles, not every collaborator.
- Dependency injection makes all of this easy (Dependency injection).
Test-driven development (TDD)
- Red: write a small failing test for the next bit of behaviour.
- Green: write the simplest code that makes it pass.
- Refactor: clean up code and tests while everything stays green.
Benefits: forces you to think about the interface and expected behaviour first; produces testable, decoupled designs; leaves a regression suite behind; keeps steps small. It works best for logic with clear inputs and outputs; for exploratory UI work or spikes, many teams write tests after but before merging. Behaviour-driven development (BDD) extends this with Given–When–Then specs shared with non-engineers.
Beyond example-based tests
Property-based testing
Instead of hand-picked examples, state a property that must hold for all inputs; the framework generates hundreds of random inputs and shrinks failures to a minimal counterexample.
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) # same length
assert all(a <= b for a, b in zip(out, out[1:])) # ordered
assert sorted(out) == sorted(xs) # same elements
@given(st.text())
def test_encode_decode_roundtrip(s):
assert decode(encode(s)) == s # round-trip propertyGreat for parsers, serializers, data structures and algorithms. Tools: Hypothesis (Python), fast-check (JS), jqwik (Java), proptest (Rust).
Other techniques
- Mutation testing (Stryker, PIT, mutmut): automatically introduce bugs (flip
<to<=) and check whether tests catch them — measures test quality, not just coverage. - Fuzzing: feed random or malformed input to find crashes and security bugs (libFuzzer, AFL, Go's built-in fuzzing).
- Snapshot / golden tests: compare output with a stored version — useful but easy to rubber-stamp; keep snapshots small.
- Contract tests: consumer-driven contracts let microservices evolve independently (Microservices).
- Visual regression tests for UI; accessibility checks with axe (Accessibility).
- Load and stress tests (k6, Gatling, Locust) before launches.
Coverage
Code coverage measures which lines or branches tests execute. It's useful for finding untested code, but high coverage doesn't mean good tests — a test can execute every line and assert nothing. Treat coverage as a signal (e.g. watch that new code is covered), not a target to game. 70–90% on business logic is typical; 100% everywhere is rarely worth it.
Flaky tests
A flaky test sometimes passes and sometimes fails without code changes. Causes: timing and sleep-based waits, test order dependence, shared state, real network calls, time zones and dates, randomness, concurrency, resource leaks.
Fixes: wait for conditions rather than fixed delays (Playwright's auto-waiting), isolate state, control time and randomness, use hermetic environments. Quarantine flaky tests immediately and fix them — flakiness destroys trust in the whole suite.
Testing in production
Pre-production testing can't reproduce real traffic, data and scale. Complement it with:
- Canary releases and feature flags (CI/CD).
- Synthetic monitoring: scripted user journeys run continuously against production.
- Observability: detect what tests missed (Observability).
- Chaos engineering: deliberately inject failures to test resilience (Monitoring and SRE).
- Tests enable fearless change; aim for maximum confidence per unit of maintenance cost.
- Pyramid: many fast unit tests, some integration and contract tests, few E2E tests.
- Good tests: AAA structure, one behaviour each, test behaviour not implementation, deterministic, independent, fast.
- Use stubs, fakes and mocks at boundaries you own; prefer real infrastructure for databases; don't over-mock.
- TDD: red, green, refactor. Property-based, mutation and fuzz testing find bugs examples miss.
- Coverage is a signal, not a goal; fix flaky tests immediately; complement with canaries and monitoring in production.
QWhat's the difference between a mock and a stub?easy
A stub provides canned responses so the code under test can run — for example, returning a fixed exchange rate — and the test asserts on the code's output or state. A mock is set up with expectations about how it will be called, and the test verifies those interactions, such as that an email service was called once with a given address. Stubs support state-based testing; mocks support interaction-based testing. Overusing mocks couples tests to implementation details.