Programming Search⌘K

Conceptcore

Unit testing

Also called unit test, developer testing.

A unit test runs one small part of a program, such as a function or a class, in isolation from the rest. It checks the result automatically and reports pass or fail in milliseconds.

Applies to
core-languages

Idea

A unit test is a small program that calls one part of another program and checks the result. The part under test is the unit: a function, a method, a class, or a small group of classes that work together. The test gives the unit a known input, runs it, and compares what it gets with what it expects. It passes or fails without a person who reads the output.

The idea answers one question: after a change, does each small part still do what it did before? A person can test a program by hand, but that check is slow, and the person cannot repeat it after each change. A unit test is code, so the machine repeats it in milliseconds, as often as needed. A suite of such tests turns "I think this still works" into a fact that the machine checks.

What counts as a unit is a decision of the team, not a rule. Martin Fowler writes that object-oriented code often takes the class as the unit, and functional code often takes the function, but that the team decides what makes sense.3 The more stable part of the definition is the isolation. Michael Feathers gave a rule of thumb in 2005: a test is not a unit test if it talks to the database, communicates across the network, touches the file system, cannot run at the same time as the other unit tests, or needs special changes to the environment to run.4 He did not call such tests bad. He wanted them kept apart, so that the unit tests stay fast.

How it works

Each test has the same four parts. Gerard Meszaros calls this the four-phase test: set up the fixture, exercise the system under test, verify the result, and tear down the fixture.5 The fixture is the state the test needs, such as an object, a list or a fake clock. In the examples on this page, the fixture is a list of (price, quantity) pairs, the exercise is a call to cart_total, and the verify step is an assertion.

A test framework does four jobs around these tests. It finds the tests, often by a name prefix (test_ in Python, Test in Go) or by an annotation (@Test in Java, #[test] in Rust, [Fact] in C#). It runs each test apart from the others, so that one failure does not stop the rest. It classifies each result. And it reports the counts, and the details of each failure. The program below does these four jobs in about 20 lines:

def cart_total(items):
    total = 0
    for price, quantity in items:
        if quantity < 0:
            raise ValueError(f"negative quantity: {quantity}")
        total += price * quantity
    return total


def test_empty_cart_is_zero():
    assert cart_total([]) == 0


def test_sums_price_times_quantity():
    assert cart_total([(250, 2), (100, 1)]) == 600


def test_wrong_expectation():
    assert cart_total([(250, 2)]) == 600  # a mistake in the test


def test_bad_input():
    cart_total([(250, None)])  # None < 0 raises TypeError


def run(tests):
    counts = {"pass": 0, "fail": 0, "error": 0}
    for test in tests:
        try:
            test()
        except AssertionError:
            outcome = "fail"
        except Exception as error:
            outcome = f"error ({type(error).__name__})"
        else:
            outcome = "pass"
        counts[outcome.split()[0]] += 1
        print(f"{test.__name__}: {outcome}")
    print(counts)


tests = [value for name, value in globals().items() if name.startswith("test_")]
run(tests)
Output
test_empty_cart_is_zero: pass
test_sums_price_times_quantity: pass
test_wrong_expectation: fail
test_bad_input: error (TypeError)
{'pass': 2, 'fail': 1, 'error': 1}

The runner finds the tests by their names. It catches the exception of each test, so the third test does not stop the fourth. It also keeps two kinds of bad result apart. A failure is a check that did not hold: the test ran to its assertion, and the value was wrong. An error is an exception that the test did not expect: here, None < 0 raises TypeError before any check runs. Kent Beck made this distinction in the first description of his Smalltalk framework. He called a failure an anticipated problem and an error a problem that the test did not check for.1 The distinction still shows in the report of unittest, which prints F for a failure and E for an error.6

A test checks a fact with an assertion. An assertion is a call that does nothing when its condition holds and stops the test with a message when it does not. Frameworks give a set of them: equality, identity, an expected exception, a value close to another within a tolerance. Some languages use a statement of the language: Python assert, the Rust macros assert! and assert_eq!. A good assertion message shows both values, so the reader knows what went wrong without a debugger. The Python assert statement does nothing when Python runs with the -O option, so production code must not depend on it.14

Tests also need to see the unit. In Rust, the usual unit test is a tests module in the same file as the code, marked #[cfg(test)], which lets it call private functions.8 In Go, the tests are in a file whose name ends in _test.go, in the same package, so they can use the names that are not exported.9 In Java and C#, the tests are in a separate class, often in a separate source tree. They call the public members, or the members that the language opens to tests: package-private members in Java, and internal members with the InternalsVisibleTo attribute in C#.

In languages

LanguageVerdictNote
PythonStandard library
C++Library
JavaLibrary
CIdiom
C#Library
JavaScriptStandard library
TypeScriptStandard library
GoStandard library
RustNative
KotlinLibraryThe Kotlin standard library has no test runner; kotlin.test is a separate library that runs on JUnit or TestNG. Alternative: Kotlin.test or JUnit Jupiter, run by Gradle or Maven.
SQLLibraryStandard SQL has no test framework. Alternative: PgTAP for PostgreSQL, tSQLt for SQL Server, or queries that compare results with expected rows.
BashLibraryBash has no test framework; a test is a script that checks exit statuses. Alternative: Bats-core, or a script with set -e and the test command.
PowerShellLibraryPowerShell has no test framework in the language or its core modules. Alternative: The Pester module, with Describe, It and Should.
HTMLDoes not applyMarkup has no units to call; it is tested through a browser.
CSSDoes not applyStyle rules have no units to call; they are tested through a browser.
Regular expressionsDoes not applyA pattern is tested through the language that uses it.

The example files show the same unit and the same three tests in each language: a cart with no items has a total of zero, the total is the sum of price times quantity, and a negative quantity is an error. The table gives the verdict for each tier 1 language.

Language Verdict Form
Python stdlib unittest; pytest is a library
JavaScript stdlib node:test and node:assert in Node.js; Jest, Vitest and Mocha are libraries
TypeScript stdlib the JavaScript runners, with types
Java library JUnit; TestNG
C idiom a test program with assert; Unity, CMocka and Check are libraries
C++ library GoogleTest; Catch2
C# library xUnit.net, NUnit or MSTest, run by dotnet test
Go stdlib package testing and the command go test
Rust native the #[test] attribute and the libtest harness, run by cargo test
Kotlin library kotlin.test on top of JUnit
PowerShell library Pester
Bash library bats-core
SQL library pgTAP for PostgreSQL; tSQLt for SQL Server
Regex n/a a pattern is tested by the language that uses it
HTML/CSS n/a markup and style rules are tested through a browser

Python's unittest follows JUnit. Its documentation says that it was originally inspired by JUnit, and it has the same parts: test fixture, test case, test suite and test runner.6 Node.js has the module node:test, which registers tests with a function call and reports them with a reporter.7 Rust is the one language in the table where the compiler itself knows about tests: rustc --test builds a harness from the functions marked #[test].8 Go puts the runner in the toolchain: go test builds a test binary from the _test.go files and runs it, and t.Run makes a subtest for each row of a table of cases.9 In Java, C# and C++, the test framework is a library. JUnit finds methods with the @Test annotation,10 xUnit.net finds [Fact] and [Theory] methods,11 and GoogleTest registers each TEST macro with its runner.12

PythonGitHub
import unittest


def cart_total(items):
    """Return the total in cents of a list of (price, quantity) pairs."""
    total = 0
    for price, quantity in items:
        if quantity < 0:
            raise ValueError(f"negative quantity: {quantity}")
        total += price * quantity
    return total


class CartTotalTest(unittest.TestCase):
    def test_empty_cart_is_zero(self):
        self.assertEqual(cart_total([]), 0)

    def test_sums_price_times_quantity(self):
        self.assertEqual(cart_total([(250, 2), (100, 1)]), 600)

    def test_rejects_negative_quantity(self):
        with self.assertRaises(ValueError):
            cart_total([(250, -1)])


if __name__ == "__main__":
    unittest.main()
Error output
test_empty_cart_is_zero (test_main.CartTotalTest.test_empty_cart_is_zero) ... ok
test_rejects_negative_quantity (test_main.CartTotalTest.test_rejects_negative_quantity) ... ok
test_sums_price_times_quantity (test_main.CartTotalTest.test_sums_price_times_quantity) ... ok

----------------------------------------------------------------------
Ran 3 tests in $TIME

OK
  • Verdict: stdlib. The unittest module is part of the standard library. A test case is a subclass of unittest.TestCase, and each method whose name starts with test is one test.
  • unittest writes its report to standard error. Each dot is one test that passed. A failure prints F and an error prints E, followed by a traceback.
  • assertRaises used as a context manager checks that the block raises the exception. The test fails when the block returns normally.
  • Many projects use pytest, which is a library. It collects plain functions whose names start with test_ and rewrites the assert statement so that a failure shows the values on each side.
#include <gtest/gtest.h>

#include <stdexcept>
#include <string>
#include <vector>

struct Item {
    int price;
    int quantity;
};

int cart_total(const std::vector<Item>& items) {
    int total = 0;
    for (const auto& item : items) {
        if (item.quantity < 0) {
            throw std::invalid_argument("negative quantity: " + std::to_string(item.quantity));
        }
        total += item.price * item.quantity;
    }
    return total;
}

TEST(CartTotal, EmptyCartIsZero) {
    EXPECT_EQ(cart_total({}), 0);
}

TEST(CartTotal, SumsPriceTimesQuantity) {
    EXPECT_EQ(cart_total({{250, 2}, {100, 1}}), 600);
}

TEST(CartTotal, RejectsNegativeQuantity) {
    EXPECT_THROW(cart_total({{250, -1}}), std::invalid_argument);
}
Output
Running main() from gtest_main.cc
[==========] Running 3 tests from 1 test suite.
[----------] Global test environment set-up.
[----------] 3 tests from CartTotal
[ RUN      ] CartTotal.EmptyCartIsZero
[       OK ] CartTotal.EmptyCartIsZero ($TIME)
[ RUN      ] CartTotal.SumsPriceTimesQuantity
[       OK ] CartTotal.SumsPriceTimesQuantity ($TIME)
[ RUN      ] CartTotal.RejectsNegativeQuantity
[       OK ] CartTotal.RejectsNegativeQuantity ($TIME)
[----------] 3 tests from CartTotal ($TIME total)

[----------] Global test environment tear-down
[==========] 3 tests from 1 test suite ran. ($TIME total)
[  PASSED  ] 3 tests.
  • Verdict: library. The C++ standard library has no test framework. GoogleTest and Catch2 are the usual libraries.
  • TEST(Suite, Name) defines one test. The library gtest_main supplies a main function that runs all tests, which is why the file has none.
  • EXPECT_EQ records a failure and goes on. ASSERT_EQ records a failure and returns from the test function at once.
  • EXPECT_THROW checks that the expression throws an exception of the given type.
  • This block does not run on this page, because it needs the GoogleTest headers and libraries, and the runner of this site builds one file with the standard library only.
JavaGitHub
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.util.List;
import org.junit.jupiter.api.Test;

record Item(int price, int quantity) {}

final class Cart {
    private Cart() {}

    static int total(List<Item> items) {
        int total = 0;
        for (Item item : items) {
            if (item.quantity() < 0) {
                throw new IllegalArgumentException("negative quantity: " + item.quantity());
            }
            total += item.price() * item.quantity();
        }
        return total;
    }
}

class CartTest {
    @Test
    void emptyCartIsZero() {
        assertEquals(0, Cart.total(List.of()));
    }

    @Test
    void sumsPriceTimesQuantity() {
        assertEquals(600, Cart.total(List.of(new Item(250, 2), new Item(100, 1))));
    }

    @Test
    void rejectsNegativeQuantity() {
        assertThrows(IllegalArgumentException.class, () -> Cart.total(List.of(new Item(250, -1))));
    }
}
Output
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│  └─ CartTest ✔
│     ├─ emptyCartIsZero() ✔
│     ├─ rejectsNegativeQuantity() ✔
│     └─ sumsPriceTimesQuantity() ✔
└─ JUnit Vintage ✔

Test run finished after $TIME
[         4 containers found      ]
[         0 containers skipped    ]
[         4 containers started    ]
[         0 containers aborted    ]
[         4 containers successful ]
[         0 containers failed     ]
[         3 tests found           ]
[         0 tests skipped         ]
[         3 tests started         ]
[         0 tests aborted         ]
[         3 tests successful      ]
[         0 tests failed          ]
  • Verdict: library. The Java standard library has no test framework. JUnit is the usual one. Its programming model, JUnit Jupiter, is in the org.junit.jupiter packages. Maven and Gradle run it in their test phase, and the console launcher runs it from the command line.
  • A test is a method with the @Test annotation. The test class and its methods need not be public.
  • assertThrows runs the lambda and fails when it does not throw an exception of the given class. It returns the exception, so a test can check its message.
  • The Java assert statement is not a replacement: the JVM skips it unless it runs with the -ea option.
  • This block does not run on this page, because it needs the JUnit library and its launcher, and the runner of this site has the standard library only.
#include <assert.h>
#include <stdio.h>

struct item {
    int price;
    int quantity;
};

/* Writes the total to *total and returns 0, or returns -1 for a negative quantity. */
static int cart_total(const struct item *items, int count, int *total) {
    int sum = 0;
    for (int i = 0; i < count; i++) {
        if (items[i].quantity < 0) {
            return -1;
        }
        sum += items[i].price * items[i].quantity;
    }
    *total = sum;
    return 0;
}

static void test_empty_cart_is_zero(void) {
    int total = -1;
    assert(cart_total(NULL, 0, &total) == 0);
    assert(total == 0);
}

static void test_sums_price_times_quantity(void) {
    const struct item items[] = {{250, 2}, {100, 1}};
    int total = 0;
    assert(cart_total(items, 2, &total) == 0);
    assert(total == 600);
}

static void test_rejects_negative_quantity(void) {
    const struct item items[] = {{250, -1}};
    int total = 0;
    assert(cart_total(items, 1, &total) == -1);
}

int main(void) {
    test_empty_cart_is_zero();
    test_sums_price_times_quantity();
    test_rejects_negative_quantity();
    puts("3 tests passed");
    return 0;
}
Output
3 tests passed
  • Verdict: idiom. ISO C has no test framework. The usual minimal form is a test program: one function for each test, assert for each check, and a main that calls the tests.
  • assert prints the failed expression, the file and the line, and then calls abort. So the first failure stops the whole program, and the tests after it do not run.
  • The macro NDEBUG turns every assert into nothing. A test build must not define it.
  • Libraries such as Unity, CMocka and Check add test registration, a report of each test, and checks that go on after a failure.
using Xunit;

public record Item(int Price, int Quantity);

public static class Cart
{
    public static int Total(IEnumerable<Item> items)
    {
        var total = 0;
        foreach (var item in items)
        {
            if (item.Quantity < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(items), $"negative quantity: {item.Quantity}");
            }
            total += item.Price * item.Quantity;
        }
        return total;
    }
}

public class CartTests
{
    [Fact]
    public void EmptyCartIsZero()
    {
        Assert.Equal(0, Cart.Total([]));
    }

    [Theory]
    [InlineData(250, 2, 500)]
    [InlineData(100, 1, 100)]
    public void MultipliesPriceByQuantity(int price, int quantity, int expected)
    {
        Assert.Equal(expected, Cart.Total([new Item(price, quantity)]));
    }

    [Fact]
    public void RejectsNegativeQuantity()
    {
        Assert.Throws<ArgumentOutOfRangeException>(() => Cart.Total([new Item(250, -1)]));
    }
}
Output
Test run for $WORK/bin/Debug/net10.0/Cart.Tests.dll (.NETCoreApp,Version=v10.0)
A total of 1 test files matched the specified pattern.

Passed!  - Failed:     0, Passed:     4, Skipped:     0, Total:     4, Duration: $TIME - Cart.Tests.dll (net10.0)
  • Verdict: library. .NET has no test framework in its base class library. xUnit.net, NUnit and MSTest are packages, and dotnet test runs any of them through the test platform.
  • [Fact] marks a test with no parameters. [Theory] marks a test that runs once for each [InlineData] row, so the report counts 4 tests for the 3 methods.
  • xUnit.net makes a separate instance of the test class for each test. The constructor is the setup step, and Dispose is the teardown step.
  • This block does not run on this page, because it needs a test project and packages from NuGet, and the runner of this site builds one file with the standard library only.
JavaScriptGitHub
import { test } from "node:test";
import assert from "node:assert/strict";

function cartTotal(items) {
  let total = 0;
  for (const [price, quantity] of items) {
    if (quantity < 0) {
      throw new RangeError(`negative quantity: ${quantity}`);
    }
    total += price * quantity;
  }
  return total;
}

test("empty cart is zero", () => {
  assert.equal(cartTotal([]), 0);
});

test("sums price times quantity", () => {
  assert.equal(cartTotal([[250, 2], [100, 1]]), 600);
});

test("rejects negative quantity", () => {
  assert.throws(() => cartTotal([[250, -1]]), RangeError);
});
Output
✔ empty cart is zero ($TIME)
✔ sums price times quantity ($TIME)
✔ rejects negative quantity ($TIME)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms $TIME
  • Verdict: stdlib. Node.js has the test runner node:test and the assertion module node:assert in its standard library. Run the file with node, or run node --test to find and run all test files.
  • Each call to test registers one test with a name and a function. The runner reports each test with its duration, then the totals.
  • In the strict mode of node:assert, assert.equal compares with Object.is, so assert.equal("1", 1) fails.
  • The ECMAScript standard has no test runner, and browsers have none. Many projects use a test library such as Jest, Vitest or Mocha.
TypeScriptGitHub
import { test } from "node:test";
import assert from "node:assert/strict";

type Item = readonly [price: number, quantity: number];

function cartTotal(items: readonly Item[]): number {
  let total = 0;
  for (const [price, quantity] of items) {
    if (quantity < 0) {
      throw new RangeError(`negative quantity: ${quantity}`);
    }
    total += price * quantity;
  }
  return total;
}

test("empty cart is zero", () => {
  assert.equal(cartTotal([]), 0);
});

test("sums price times quantity", () => {
  assert.equal(cartTotal([[250, 2], [100, 1]]), 600);
});

test("rejects negative quantity", () => {
  assert.throws(() => cartTotal([[250, -1]]), RangeError);
});
Output
✔ empty cart is zero ($TIME)
✔ sums price times quantity ($TIME)
✔ rejects negative quantity ($TIME)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms $TIME
  • Verdict: stdlib. TypeScript has no test runner of its own. It uses the runners of JavaScript, and the type checker adds types to the tests: here node:test and node:assert, run by Node.js after it strips the types.
  • The type checker catches some mistakes before the tests run. A call such as cartTotal(250) is a type error, so no test is needed for it.
  • The type checker does not check values. A negative quantity is a valid number, so the range check still needs a test.
package cart

import "fmt"

// Item is one line of a cart: a price in cents and a quantity.
type Item struct {
	Price    int
	Quantity int
}

// Total returns the total of the items in cents.
func Total(items []Item) (int, error) {
	total := 0
	for _, item := range items {
		if item.Quantity < 0 {
			return 0, fmt.Errorf("negative quantity: %d", item.Quantity)
		}
		total += item.Price * item.Quantity
	}
	return total, nil
}
package cart

import "testing"

func TestTotal(t *testing.T) {
	tests := []struct {
		name  string
		items []Item
		want  int
	}{
		{"empty cart is zero", nil, 0},
		{"sums price times quantity", []Item{{250, 2}, {100, 1}}, 600},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := Total(tt.items)
			if err != nil {
				t.Fatalf("Total(%v) returned error %v", tt.items, err)
			}
			if got != tt.want {
				t.Errorf("Total(%v) = %d, want %d", tt.items, got, tt.want)
			}
		})
	}
}

func TestTotalRejectsNegativeQuantity(t *testing.T) {
	if _, err := Total([]Item{{250, -1}}); err == nil {
		t.Error("Total with quantity -1 returned no error")
	}
}
Output
=== RUN   TestTotal
=== RUN   TestTotal/empty_cart_is_zero
=== RUN   TestTotal/sums_price_times_quantity
--- PASS: TestTotal ($TIME)
    --- PASS: TestTotal/empty_cart_is_zero ($TIME)
    --- PASS: TestTotal/sums_price_times_quantity ($TIME)
=== RUN   TestTotalRejectsNegativeQuantity
--- PASS: TestTotalRejectsNegativeQuantity ($TIME)
PASS
ok  	example	$TIME
  • Verdict: stdlib. The testing package and the go test command are part of the Go distribution. A file whose name ends in _test.go holds the tests, and go build leaves it out.
  • A test is a function TestXxx(t *testing.T). t.Errorf records a failure and goes on, and t.Fatalf records a failure and stops the test.
  • Go has no assertion functions in the standard library. The test compares the values with if and writes its own message. Libraries such as testify add assertions.
  • The table of cases with t.Run for each case is the usual form of a Go test. Each case is a subtest with its own name in the report.
  • These blocks do not run on this page, because go test builds the test binary and its main function, and the runner of this site runs go build on one main package.
RustGitHub
pub fn cart_total(items: &[(i64, i64)]) -> Result<i64, String> {
    let mut total = 0;
    for &(price, quantity) in items {
        if quantity < 0 {
            return Err(format!("negative quantity: {quantity}"));
        }
        total += price * quantity;
    }
    Ok(total)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn empty_cart_is_zero() {
        assert_eq!(cart_total(&[]), Ok(0));
    }

    #[test]
    fn sums_price_times_quantity() {
        assert_eq!(cart_total(&[(250, 2), (100, 1)]), Ok(600));
    }

    #[test]
    fn rejects_negative_quantity() {
        assert_eq!(
            cart_total(&[(250, -1)]),
            Err("negative quantity: -1".to_string())
        );
    }
}
Output

running 3 tests
test tests::empty_cart_is_zero ... ok
test tests::rejects_negative_quantity ... ok
test tests::sums_price_times_quantity ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME
  • Verdict: native. The #[test] attribute is part of the language, and the compiler builds a test harness from the functions that carry it. cargo test builds the crate with rustc --test and runs the result; this page runs rustc --test directly.
  • #[cfg(test)] compiles the tests module only in the test build, so the tests add nothing to the release binary. A unit test in the same file can call private functions of the module.
  • The harness runs tests on several threads by default, so the order of the lines can change. With the option --test-threads=1, it runs them one at a time in the order of their names.
  • A test fails when it panics. assert_eq! panics with both values when they differ. The attribute #[should_panic] reverses this for a test that must panic.

Solitary and sociable tests. A solitary test replaces each collaborator of the unit with a test double, so that a fault in one class fails only the tests of that class. A sociable test uses the real collaborators. Fowler credits the two terms to Jay Fields, and he writes that early xUnit tests were mostly sociable.3 The two styles go with two schools: the mockist school prefers solitary tests, and the classic school prefers sociable ones.3

Test doubles. A test double is an object that takes the place of a real collaborator in a test. Meszaros groups them into dummies, stubs, spies, mocks and fakes.5 A double makes the test fast, and it makes a slow or random collaborator (a network, a clock, a random number generator) fixed. The cost is that the test checks the unit against the double, and the double can be wrong about the real collaborator.

Parameterized tests. One test function runs once for each row of a table of inputs and expected outputs. Go writes the table as a slice of structs and calls t.Run for each row.9 xUnit.net uses [Theory] with an [InlineData] attribute for each row.11 Each row is a separate test in the report.

Test-driven development. In test-driven development, the programmer writes a unit test before the code, sees it fail, writes the code that makes it pass, and then refactors. Fowler describes unit testing as a signature practice of Extreme Programming, which led to test-driven development.3 Unit tests are also what makes refactoring safe: a refactoring such as extract function keeps behaviour, and the tests check that it did.

Other levels of testing. Integration tests check that units work together and with real services, such as a database. End-to-end tests drive the whole system, often through its user interface. The test pyramid, which Fowler attributes to Mike Cohn, says that a suite should have many more unit tests than broad tests through a user interface, because the broad tests are slower, more expensive to write and more brittle.13

Pitfalls

Tests that share state. When two tests use the same mutable object, the result of one depends on whether the other ran first:

This code runs but gives a wrong answer on purpose.

cart = []  # shared by every test


def test_new_cart_is_empty():
    assert cart == []


def test_add_one_item():
    cart.append((250, 2))
    assert sum(price * quantity for price, quantity in cart) == 500


def run(name, tests):
    cart.clear()  # as if each run were a fresh process
    print(name)
    for test in tests:
        try:
            test()
            print(f"  {test.__name__}: pass")
        except AssertionError:
            print(f"  {test.__name__}: fail")


run("order 1", [test_new_cart_is_empty, test_add_one_item])
run("order 2", [test_add_one_item, test_new_cart_is_empty])
Output
order 1
  test_new_cart_is_empty: pass
  test_add_one_item: pass
order 2
  test_add_one_item: pass
  test_new_cart_is_empty: fail

Both tests are correct alone. In the second order, test_add_one_item leaves an item in the shared cart, and test_new_cart_is_empty fails. A runner that changes the order, or runs tests on several threads, exposes the bug at random. The fix is a fixture for each test: each test makes its own cart. xUnit.net makes a separate instance of the test class for each test, and unittest calls setUp before each test method.611

Tests that depend on the clock, on chance or on the outside world. A test that calls sleep, reads the time of day, uses an unseeded random number, or calls a server can pass today and fail tomorrow with no change to the code. Such a test is called flaky. The fix is to pass the dependency in, so that the test can give a fixed one:

import time


class Session:
    def __init__(self, lifetime, clock=time.monotonic):
        self.clock = clock
        self.expires = clock() + lifetime

    def expired(self):
        return self.clock() >= self.expires


class FakeClock:
    def __init__(self):
        self.now = 1000

    def __call__(self):
        return self.now


def test_session_expires_after_its_lifetime():
    clock = FakeClock()
    session = Session(lifetime=30, clock=clock)
    assert not session.expired()
    clock.now += 29
    assert not session.expired()
    clock.now += 1
    assert session.expired()


test_session_expires_after_its_lifetime()
print("pass: no sleep, same result on every run")
Output
pass: no sleep, same result on every run

The session takes the clock as a parameter, with the real clock as the default. The test passes a fake clock and moves it by hand, so it checks the edge of the lifetime exactly and needs no wait.

Tests that check the implementation instead of the behaviour. A test that asserts which private methods were called, or in which order a mock was used, fails when the code changes in a way that keeps the result. Such tests make refactoring expensive, because each change breaks tests that found no bug. Test the result that a caller can see.

Tests that cannot fail. A test with no assertion, or one that catches the exception it should let out, passes for any code. Watch each test fail once, for example by breaking the code on purpose, before trusting it.

Too much in one test. A test that checks ten things stops at the first failure, and its name cannot say what broke. One behaviour for each test, with a name that states it (rejects_negative_quantity), makes the report read as a list of facts.

Cost

A unit test runs in the same process as the code, with no disk and no network, so its cost is close to the cost of the calls it makes. In the runs on this page, unittest reports 3 tests in less than a millisecond, and node:test reports each test in about a millisecond or less. The start of the process and the build cost more than the tests: a test binary in Rust, Go, Java, C# or C++ must be compiled before it runs. Fowler cites the rule of thumb of Kent Beck that the suite that runs before each commit should take no more than ten minutes.3 Feathers keeps the slow tests in a separate set for the same reason: a fast set of tests can run after every change.4

The larger cost is the code itself. Tests are code that the team must read, keep in step with the program and fix when they break for reasons that are not bugs. A test that is coupled to the implementation multiplies this cost with each refactoring. Isolation also has a cost: each test double is code that can drift from the real collaborator, and a suite of solitary tests can pass while the units fail to work together. Integration tests cover that gap.

History

Kent Beck described a testing framework for Smalltalk in his column "Simple Smalltalk Testing: With Patterns" in The Smalltalk Report in 1994.1 The column states the patterns that later frameworks kept: a fixture, a test case, a check, and a test suite that collects test cases. The framework became known as SUnit. Fowler writes that the idea started in Smalltalk but stayed mostly unknown outside the Smalltalk community.2

According to Fowler, Beck and Erich Gamma wrote the first version of JUnit on a flight to the OOPSLA conference in 1997, as a pair, and test first.2 JUnit spread the idea to Java and then to other languages. The family took the name xUnit from it, and Fowler writes that JUnit was essential to the growth of Extreme Programming and test-driven development.2 Python's unittest names JUnit as its model.6

In 2005, Feathers published his rules for what is not a unit test.4 In 2007, Meszaros collected the patterns and the names of the xUnit style, such as the four-phase test and the kinds of test double, in xUnit Test Patterns.5 Later, test runners moved into language toolchains: Go ships go test, Rust has #[test] and cargo test, and Node.js has node:test.789

References

  1. Kent Beck, Simple Smalltalk Testing, With Patterns, The Smalltalk Report, 1994, the patterns Fixture, Test Case, Check and Test Suite; failures and errors
  2. Martin Fowler, Xunit, bliki, 17 January 2006, the origin of SUnit and JUnit
  3. Martin Fowler, Unit Test, bliki, 5 May 2014, what a unit is; solitary and sociable tests; speed
  4. Michael Feathers, A Set of Unit Testing Rules, Artima Weblogs, 9 September 2005, the list of things that make a test not a unit test
  5. Gerard Meszaros, xUnit Test Patterns, Refactoring Test Code, Addison-Wesley, 2007, Chapter 19, xUnit Basics Patterns, Four-Phase Test (page 358); Test Double
  6. The Python Standard Library, unittest, introduction; test fixture, test case, test suite, test runner
  7. Node.js documentation, Test runner (node:test), introduction; test reporters
  8. The Rust Programming Language, 11.3 Test Organization, Unit Tests; The Tests Module and
  9. Go standard library, package testing, package overview; T.Run (subtests)
  10. JUnit User Guide, Writing Tests; Test Classes and Methods
  11. xUnit.net documentation, Getting Started, Fact and Theory
  12. GoogleTest Primer, Assertions (EXPECT and ASSERT); Simple Tests
  13. Martin Fowler, Test Pyramid, bliki, 1 May 2012, the shape of a test suite; Mike Cohn, Succeeding with Agile (2009)
  14. The Python Language Reference, The assert statement, 7.3 The assert statement (__debug__ and -O)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/9JTT3Z/text.yaml