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:
- Arrange: set up the input.
- Act: call the code under test.
- 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}"const assert = require('node:assert');
function slugify(title) {
return title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
}
// A table-driven test: each row is an input and the output we expect.
// With node:test or Vitest, this body goes inside test('slugify', () => { ... }).
function testSlugify() {
const cases = [
['Hello World', 'hello-world'],
[' Big O, explained! ', 'big-o-explained'],
['C++ & Rust', 'c-rust'],
['', ''],
];
for (const [title, want] of cases) {
assert.strictEqual(slugify(title), want, `slugify(${JSON.stringify(title)})`);
}
}import (
"fmt"
"regexp"
"strings"
)
var nonAlnum = regexp.MustCompile(`[^a-z0-9]+`)
func slugify(title string) string {
return strings.Trim(nonAlnum.ReplaceAllString(strings.ToLower(title), "-"), "-")
}
// A table-driven test: each row is an input and the output we expect.
// In a _test.go file this is func TestSlugify(t *testing.T), reporting
// with t.Errorf, and `go test` runs it.
func testSlugify() error {
cases := []struct{ title, want string }{
{"Hello World", "hello-world"},
{" Big O, explained! ", "big-o-explained"},
{"C++ & Rust", "c-rust"},
{"", ""},
}
for _, c := range cases {
if got := slugify(c.title); got != c.want {
return fmt.Errorf("slugify(%q) = %q, want %q", c.title, got, c.want)
}
}
return nil
}fn slugify(title: &str) -> String {
let mut slug = String::new();
for c in title.to_lowercase().chars() {
if c.is_ascii_alphanumeric() {
slug.push(c);
} else if !slug.is_empty() && !slug.ends_with('-') {
slug.push('-');
}
}
slug.trim_end_matches('-').to_string()
}
// A table-driven test: each row is an input and the output we expect.
// Put #[test] above it and `cargo test` runs it.
fn test_slugify() {
let cases = [
("Hello World", "hello-world"),
(" Big O, explained! ", "big-o-explained"),
("C++ & Rust", "c-rust"),
("", ""),
];
for (title, want) in cases {
assert_eq!(slugify(title), want, "slugify({:?})", title);
}
}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
- Testing the implementation, not the behaviour. A test that checks which private methods were called breaks on every refactor. Test inputs and outputs.
- Chasing 100% coverage. Coverage shows which lines ran, not whether the asserts were any good. A test with no asserts can cover everything.
- Flaky tests. A test that sometimes fails, because of timing, randomness or test order, teaches people to ignore red. Fix it or delete it.
- 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?
It tests one piece of logic in isolation, with its dependency replaced by a fake. Using the real payment service would make it an integration test.
Check yourself
Your suite has 100% line coverage. What does that guarantee?
Coverage only measures which lines executed. Whether the tests checked the right results depends on their asserts.
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.
Finished this page?
Your list