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.

Intermediate 6 min readLesson 4 of 9 Interview Q&A

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

LevelTestsSpeedConfidenceExample
UnitOne function or class in isolationMillisecondsThat the logic is rightcalculateDiscount returns 10% for gold members
IntegrationSeveral components together, often with real infrastructureSecondsThat the pieces fitRepository code against a real PostgreSQL in a container
ContractThe agreement between a consumer and a providerFastThat services remain compatiblePact tests between the web app and the orders API
End-to-end (E2E)The whole system through its UI or APISlowThat user journeys workPlaywright: sign up, add to cart, check out
Non-functionalPerformance, load, security, accessibilityVariesThat it's fast, secure, usablek6 load test; OWASP ZAP scan; axe checks

The test pyramid

E2Efew — critical user journeys onlyIntegration / contractsome — boundaries: databases, queues, APIsUnitmany — fast, focused, deterministic

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

Python
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:

DoubleWhat it doesExample
DummyFills a parameter; never usedNone logger
StubReturns canned answersExchange-rate service always returns 83.2
FakeA working lightweight implementationIn-memory repository; SQLite instead of Postgres
MockVerifies interactions — expected calls"Email service was called once with this address"
SpyRecords calls on a real object for later assertions—
TypeScript
// 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 PaymentGateway interface), 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)

  1. Red: write a small failing test for the next bit of behaviour.
  2. Green: write the simplest code that makes it pass.
  3. 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.

Python
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 property

Great 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).
Key takeaways
  • 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.
Interview questions
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.