programmingconcepts

§ 8.3 · Tools

Testing

Code that runs your code with known inputs and checks the outputs, so you find bugs before your users do.

Software testing means writing code that runs your program with known inputs and checks that the results match what you expect. Unit tests check one small piece quickly, integration tests check pieces working together, and end-to-end tests drive the whole app. A good test suite lets you change code confidently, because a broken behaviour fails a test immediately.

Unit test
One function or class, in milliseconds
Integration test
Several parts together
End-to-end test
The whole app, as a user
Runners
pytest, Vitest, go test, cargo test
Requires
Functions

Why test

Without tests, every change is a gamble: you fix one thing and hope nothing else broke. A test suite turns that hope into a check that runs in seconds. It also documents behaviour. A test named rejects_expired_token tells the next developer what the code is meant to do.

Anatomy of a test

Almost every test has the same three steps, often called arrange, act, assert:

  1. Arrange: set up the input.
  2. Act: call the code under test.
  3. Assert: compare the result with what you expect, and fail loudly if it’s different.

The example tests a slugify function that turns a title into a URL fragment, like this site’s page addresses. It’s table-driven: each row is an input and the expected output, and one loop checks them all. Adding a case means adding a row.

import re


def slugify(title):
    slug = re.sub(r"[^a-z0-9]+", "-", title.lower())
    return slug.strip("-")


# A table-driven test: each row is an input and the output we expect.
# pytest runs any function named test_* and reports failed asserts.
def test_slugify():
    cases = [
        ("Hello World", "hello-world"),
        ("  Big O, explained!  ", "big-o-explained"),
        ("C++ & Rust", "c-rust"),
        ("", ""),
    ]
    for title, want in cases:
        got = slugify(title)
        assert got == want, f"slugify({title!r}) = {got!r}, want {want!r}"

Notice the rows. Two are ordinary inputs; the others are edge cases: punctuation, symbols, and an empty string. Bugs live at the edges, so most of a good test table is edge cases.

Kinds of test

Kind Checks Speed How many
Unit One function or class, with its dependencies faked Milliseconds Many
Integration Real parts together: code with a real database, two services Seconds Some
End-to-end The whole app through its UI or public API Seconds to minutes Few

This shape, many fast tests at the bottom and a few slow ones at the top, is the testing pyramid. Fast tests run on every save; slow ones run before merging.

Unit tests need a way to swap in fakes for things like the clock or the network. That’s what dependency injection is for.

Test-driven development

In TDD, you write the test first, watch it fail, write just enough code to make it pass, then clean up. Red, green, refactor. Its main benefit is that you design the function’s interface from the caller’s side before writing it. It’s a technique, not a requirement; many good teams write tests right after the code instead.

Common mistakes

  1. Testing the implementation, not the behaviour. A test that checks which private methods were called breaks on every refactor. Test inputs and outputs.
  2. Chasing 100% coverage. Coverage shows which lines ran, not whether the asserts were any good. A test with no asserts can cover everything.
  3. Flaky tests. A test that sometimes fails, because of timing, randomness or test order, teaches people to ignore red. Fix it or delete it.
  4. Only testing the happy path. Empty input, huge input, and invalid input are where bugs hide.

Check yourself

Check yourself

A test checks that checkout() charges the right amount, using a fake payment gateway. What kind of test is it?

Check yourself

Your suite has 100% line coverage. What does that guarantee?

Sources

  • Kent Beck, Test-Driven Development: By Example (2002).
  • Mike Cohn, Succeeding with Agile (2009), the source of the testing pyramid.
  • Martin Fowler, “The Practical Test Pyramid” (2018), martinfowler.com.

Newsletter

One new concept each week, by email.

Signup opens soon.