{"canonical_url":"https://engineer.company/glossary/unit-test/","content_markdown":"# Unit test\n\n## What it is\n\nA unit test is a small automated check of one piece of code on its own: it calls\na function, a class or a small module with chosen inputs and asserts that what\ncomes back is what should come back. Such tests are usually designed to run in\nthe same process as the code they check, finish quickly and need no network,\ndatabase or browser. Those are useful resource and isolation choices, not\nguarantees that follow from a test's narrow scope alone. The practice of writing\nthem is usually called unit testing, and a project's collection of them is its\nunit test suite.\n\nWhat counts as a unit is less settled than the name suggests. In the chapter on\nunit testing in _Software Engineering at Google_, Erik Kuefler uses the term for\ntests of relatively narrow scope, such as a single class or method, and adds\nthat a unit may be a single function or reach as far as several related\npackages. The useful boundary is the one other people call: a unit is whatever\noffers an interface someone outside it relies on, and its tests use that\ninterface the way its callers do.\n\nThe modern frameworks share an ancestry. Kent Beck's paper _Simple Smalltalk\nTesting: With Patterns_ described a small framework built from fixtures, test\ncases, checks and suites, and advised that developers write their unit tests\nthemselves, one for each class. Python's `unittest` says in its documentation\nthat it was originally inspired by JUnit, and it keeps the same four ideas: a\ntest fixture (the preparation a test needs and the cleanup after it), a test\ncase (the individual unit of testing), a test suite and a test runner. Both draw\na line worth keeping: a failure is a check that got the wrong answer, while an\nerror is something the test did not anticipate at all, such as an exception\nthrown from deep inside the code.\n\nUnit tests sit at the narrow end of a range. Adam Bender's chapter on testing in\nthe same book sorts tests by scope: narrow tests are commonly called unit tests,\nmedium-scoped tests that cover a few components together are integration tests,\nand large-scoped tests that drive the whole system are end-to-end tests.\n\n## Why it matters\n\nSpeed is the first reason. A small, isolated unit test runs in the same process\nas the code it checks, so an engineer can run thousands of them in an ordinary\nworking day, and a mistake shows up while the change that caused it is still on\nthe screen. Google's guidance is blunt about what it allows: a small test must\nnot sleep, perform I/O, or touch the network or the disk. Those constraints make fast,\nrepeatable tests easier to build, and a team learns to trust a suite that gives\nthe same answer every time.\n\nThe second reason is diagnosis. When a narrow test fails, the fault is in a\nsmall piece of code, usually the one just changed. When a test that drives the\nwhole system fails, the fault could be anywhere between the browser and the\ndatabase. That is why _Software Engineering at Google_ describes a pyramid as a\nrough guideline: about 80 per cent of tests narrow-scoped, 15 per cent\nintegration tests and 5 per cent end-to-end tests.\n\nThe third is change. A suite that checks behaviour through a public interface\nlets the code behind that interface be restructured without fear: if the tests\nstill pass, the callers are still served. Kuefler's ideal is a test that never\nhas to change unless the requirements change, so a pure refactoring touches no\ntest at all.\n\nUnit tests also document. A test named after a behaviour, with plain inputs and\nan expected result written out in full, shows the next reader how the code is\nmeant to be called and what it promises, and unlike a comment it fails when it\nstops being true.\n\n## What it looks like in practice\n\nTake a function that reads durations such as `1h30m` from a configuration file\nand turns them into seconds:\n\n```python\n# durations.py\nUNITS = {\"h\": 3600, \"m\": 60, \"s\": 1}\n\n\ndef to_seconds(text: str) -\u003e int:\n    \"\"\"Turn \"1h30m\" or \"45s\" into a whole number of seconds.\"\"\"\n    total, digits = 0, \"\"\n    for char in text:\n        if char.isdigit():\n            digits += char\n        elif char in UNITS and digits:\n            total += int(digits) * UNITS[char]\n            digits = \"\"\n        else:\n            raise ValueError(f\"not a duration: {text!r}\")\n    if digits or not text:\n        raise ValueError(f\"not a duration: {text!r}\")\n    return total\n```\n\nIts unit tests, written for pytest, check two behaviours: what it accepts and\nwhat it refuses.\n\n```python\n# test_durations.py\nimport pytest\n\nfrom durations import to_seconds\n\n\n@pytest.mark.parametrize(\n    \"text,expected\",\n    [(\"45s\", 45), (\"2m\", 120), (\"1h30m\", 5400), (\"0s\", 0)],\n)\ndef test_counts_each_unit(text, expected):\n    assert to_seconds(text) == expected\n\n\n@pytest.mark.parametrize(\"text\", [\"\", \"90\", \"h\", \"1x\", \"1.5h\"])\ndef test_refuses_what_it_cannot_read(text):\n    with pytest.raises(ValueError):\n        to_seconds(text)\n```\n\nRunning `pytest` in the directory collects every file named `test_*.py` or\n`*_test.py`, and the two functions expand into nine cases, one per row of\nparameters. The pytest documentation describes each test as arrange, act, assert\nand cleanup; here the arrangement is the parameter row, the act is the single\ncall, and there is nothing to clean up because nothing outside the function is\ntouched. If someone later sets the minute to 3600 seconds by mistake, two cases\nfail, and the report names each by its parameters:\n`test_counts_each_unit[2m-120]` shows 7200 against the expected 120, and\n`test_counts_each_unit[1h30m-5400]` shows 111600 against 5400. Note that the\nexpected values are worked out by hand, not copied from what the code returned\non its first run.\n\nThe same checks in the standard library's `unittest` would be a subclass of\n`unittest.TestCase` with methods whose names start with `test`, using\n`assertEqual` and `assertRaises`; `python -m unittest` finds files matching\n`test*.py` by default. Go puts the convention into the toolchain: a function\n`func TestXxx(t *testing.T)` in a file ending in `_test.go` is run by\n`go test`.\n\nScale changes the bookkeeping, not the idea. The\n[database generator held to 981 test cases](/portfolio/held-the-generator-to-981-tests-and-92-coverage/),\nwork carried out in July 2026, counts 383 test functions that become 981 cases\nonce the parameterised ones expand, across 45 files and 7,944 lines. Its build\nenforces a branch-coverage floor of 92 per cent, with about 95 per cent\nmeasured, and treats warnings as failures. The page is candid about the limit\nof the number: two defects found later sat in code the coverage report showed as\ncovered.\n\n## Where it goes wrong\n\n**The tests mirror the implementation.** A test that reaches into private\nhelpers, or asserts the exact sequence of internal calls, breaks every time the\ncode is restructured even though nothing a caller sees has changed. Kuefler\ncalls this a brittle test, and names over-reliance on mocking frameworks as the\nmost common reason that tests of interactions go wrong. Test through the public\ninterface, check the resulting state rather than the calls made to get there,\nand use real objects where they are cheap.\n\n**Tests depend on each other.** One test creates a record, the next one reads\nit, and the suite passes only in that order. Run a single test, or the same\ntests in a different order, and it fails for no reason a reader can see. Beck's\nframework created and threw away its test data for each test, and the\n`unittest` documentation asks that a test case be entirely self-contained. Give\nevery test its own fixture and clean up after it.\n\n**Coverage becomes the goal.** Coverage shows that a line ran, not that anything\nchecked what it did. A test with no assertion raises the number and proves\nnothing, and _Software Engineering at Google_ warns that an 80 per cent bar\ntends to become a ceiling, with changes landing at exactly the minimum. Treat\nthe number as a floor and read the assertions in review.\n\n**One test per method.** Matching each production method with one test method\nlooks tidy, but the test grows every time the method gains a branch, until\nnobody can say what it checks. Kuefler's advice is to test behaviours instead:\none behaviour per test, named after what it proves, so a failure report reads as\na sentence about what broke.\n\n**The test waits for time to pass.** A `sleep()` to let something finish makes\nthe suite slower on every run and still fails on a busy machine. In a unit test,\ntime is an input: pass in a clock or a timestamp, so the test can set the time\nit needs instead of waiting for it.\n\n## Further reading\n\n- [unittest: Unit testing framework](https://docs.python.org/3/library/unittest.html)\n  — the Python standard library's framework: fixtures, test cases, suites,\n  runners, discovery and the difference between a failure and an error.\n- [Anatomy of a test](https://docs.pytest.org/en/stable/explanation/anatomy.html)\n  — pytest's explanation of arrange, act, assert and cleanup.\n- [Get Started](https://docs.pytest.org/en/stable/getting-started.html)\n  — pytest's own introduction: plain `assert`, test discovery and\n  `pytest.raises`.\n- [Unit Testing](https://abseil.io/resources/swe-book/html/ch12.html)\n  — Erik Kuefler's chapter of _Software Engineering at Google_ on brittle tests,\n  public APIs, state versus interactions and testing behaviours.\n- [Simple Smalltalk Testing: With Patterns](https://web.archive.org/web/20150315073817/http://www.xprogramming.com/testfram.htm)\n  — Kent Beck's paper on the framework, the case for writing unit tests one per\n  class, and failures versus errors, in an archived copy.\n- [testing](https://pkg.go.dev/testing)\n  — Go's standard testing package: `TestXxx` functions, `_test.go` files and\n  `go test`.\n\n\u003chttps://engineer.company/glossary/unit-test/\u003e\n","date_modified":"2026-11-09T21:50:25Z","description":"What counts as a unit, how a test stays fast and independent, a worked pytest example, and the habits that make a suite brittle.","formats":{"gemtext":"https://engineer.company/glossary/unit-test/index.gmi","gopher":"https://engineer.company/glossary/unit-test/gophermap","html":"https://engineer.company/glossary/unit-test/","json":"https://engineer.company/glossary/unit-test/index.json","markdown":"https://engineer.company/glossary/unit-test/index.md","pdf":"https://engineer.company/glossary/unit-test/index.pdf"},"kind":"page","language":"en","title":"What is a unit test?","url":"https://engineer.company/glossary/unit-test/","version":1}