Search

Search papers and lessons

Unit Testing

Level 2 · 10 min read

A unit test runs one small piece of code on chosen inputs and checks the output against the expected answer, so a change that breaks that answer is caught at once.

On this page

  • Colour = topic mix
  • Programming languages
  • Discrete math
  • Algorithms
  • Systems
  • ReadReady to readNot yet

TL;DR

A unit test is a short program that calls one small piece of code, such as a function, with inputs you chose, and checks that the result equals the answer you expected. The test passes or fails with no human reading the output. A suite of such tests runs in seconds, so a developer can change code and learn at once when a behaviour has broken. Unit tests cannot prove that code is correct, but they catch many mistakes early and document what the code is meant to do.

Builds on: Function, side effects · Leads to: Formal Verification for proofs about all inputs

Where it's used

Libraries and shared code. A payments library or a date-parsing library is called by many programs. Its maintainers keep thousands of unit tests, so a change that breaks rounding or time zones fails a test before a release reaches customers.

Continuous integration. Many teams run their unit tests on every change that is proposed to a shared codebase. A typical service may run a suite of several thousand tests in a few minutes, and the change cannot be merged until they pass.

Refactoring. A developer who wants to rewrite a sorting routine can keep the old tests and run them against the new version. If all the tests still pass, the observable behaviour is the same, and the rewrite can go ahead with confidence.

How it works

Take a small Function that adds a flat delivery fee of 2 to the total of an list of prices:

def total_with_fee(prices):
    return sum(prices) + 2

Its unit test checks one known input against the answer worked out by hand.

  1. Choose an input. Use the list [10, 20]. Check: the input is small enough that you can compute the answer without the computer.
  2. Work out the expected answer. The sum is 30, and adding the fee gives 32. Check: the expected value is 32, written down before the code runs.
  3. Call the function. The code runs total_with_fee([10, 20]) and returns 32. Check: the actual value is 32.
  4. Compare. The test asserts that the actual value equals the expected value. Check: 32 equals 32, so the assertion passes.
  5. Introduce a bug. Suppose someone removes the fee, so the function returns 30. Check: the same test now compares 30 with 32 and fails.
  6. Read the failure. The test reports the input, the expected value and the actual value. Check: the developer sees at once that the fee is missing, and the bug is found before the code ships.
flowchart LR
  I[Chosen input] --> F[Call the function]
  F --> C{Actual equals expected?}
  C -- yes --> P[Test passes]
  C -- no --> X[Test fails and reports input, expected and actual]

Steps 2 and 4 are the key. The expected value must come from the specification, not from running the code, or the test only repeats the code's own mistakes.

The math

Definition: Test suite
Let ff be the function under test, and let (x1,y1),…,(xn,yn)(x_1, y_1), \dots, (x_n, y_n) be pairs of input and expected output. The suite passes when f(xi)=yif(x_i) = y_i for every ii from 1 to nn.

Step 2 in symbols: the expected value

Write the specification as a function gg that gives the correct answer. For the example, g(prices)=∑prices+2g(\text{prices}) = \sum \text{prices} + 2, where ∑\sum is the sum over the list. The expected value for the input (10,20)(10, 20) is

g(10,20)=10+20+2=32.g(10, 20) = 10 + 20 + 2 = 32.

The test pairs the input with this value, so (x1,y1)=((10,20),32)(x_1, y_1) = ((10, 20), 32).

Step 4 in symbols: the assertion

The assertion is the check f(x1)=y1f(x_1) = y_1. With f(10,20)=32f(10, 20) = 32, the check is 32=3232 = 32, which holds, so the suite passes at this case.

Step 5 in symbols: a bug is a failing input

If the fee is removed, the buggy function is f′(prices)=∑pricesf'(\text{prices}) = \sum \text{prices}, so f′(10,20)=30≠32f'(10, 20) = 30 \ne 32. The test detects the bug because the input lies in the set of inputs where ff and gg disagree. A test catches a bug only if one of its inputs is in that set. The fraction of inputs covered by nn tests, over a domain of NN possible inputs, is n/Nn/N. For an integer input from 0 to 99, three tests cover 3/100=0.033/100 = 0.03 of the inputs.

Worked examples

Example
1. A tiny test, by hand

Test add(2, 3), where add returns the sum of two numbers.

  1. The expected value is 2+3=52 + 3 = 5, worked out from the definition of addition.
  2. The function returns 5.
  3. The assertion compares 5 with 5. It holds.
  4. Interpretation: the test passes, and it would fail for any function that returned something other than 5 for this input. One test proves very little about the rest of the inputs, but it shows that the function works here.
Example
2. The fee function, standard case

Two tests for total_with_fee: an empty list and the list [10, 20].

  1. Empty list: the sum of no prices is 0, and adding the fee gives 0+2=20 + 2 = 2. The function returns 2, so this test passes.
  2. The list [10, 20]: the sum is 30, and 30+2=3230 + 2 = 32. The function returns 32, so this test passes.
  3. Now the bug: the fee is removed. The empty-list test expects 2 and gets 0, so it fails. The [10, 20] test expects 32 and gets 30, so it fails too.
  4. Both tests fail for the same reason. The two cases together cover the empty and non-empty kinds of input.
  5. Interpretation: the empty-list case is worth testing because it is a boundary. A function that handles the typical case may still break on the edge.
Example
3. An email normaliser, realistic

A sign-up form calls normalize_email, which removes spaces at both ends and lowercases the address, so that [email protected] and [email protected] are the same account. The tests are:

  1. For the first test, strip the spaces: "[email protected]". Lowercase it: "[email protected]". This equals the expected value, so the test passes.
  2. For the second test, stripping and lowercasing an empty string leave it empty. The result matches the expected empty string, so this test also passes.
  3. Suppose someone removes the lowercasing step. The first test now gets "[email protected]", which differs from the expected value, and the test fails.
  4. Interpretation: the failing test shows a real problem. Two addresses that differ only in case would be stored as two accounts, which is the bug the function exists to prevent.

Try it: what does normalize_email("[email protected] ") return? Answer: "[email protected]", because the trailing spaces are removed and the letters are lowercased.

Common mistakes and tradeoffs

It is tempting to think that a test which runs the code and copies its output proves the code is right. In fact that test checks only that the code is unchanged. The expected value must come from the specification, because a test built from the code's own output agrees with any bug.

It is tempting to think that 100 percent code coverage means the code is tested well. In fact coverage shows which lines ran, not whether the checks were meaningful. A test with no assertion covers every line and proves nothing.

It is tempting to test only the typical input. In fact most bugs live at the edges: empty lists, zero, very large numbers, and repeated calls. A test suite that never tries an edge case leaves those paths unchecked.

It is tempting to mock every dependency so that a test never touches a database or a network. In fact heavy mocking can make a test pass while the real system fails, because the mock behaves as the developer imagined rather than as the real component does. Use mocks for slow or uncontrollable parts, and keep some tests against the real component. A function with side effects, such as one that writes to a database, can also leave changes that the next test sees, so its tests need setup and cleanup.

When to use unit tests. Use them for functions with clear inputs and outputs, for logic that changes often, and for any code that is shared. When not to use them. Unit tests are weak for layout, for how components look together, and for behaviour that spans many services, where integration or end-to-end tests fit better. Alternatives. A type system catches some mistakes before the code runs at all. Property-based testing generates many inputs from a rule and checks properties that must always hold. Formal verification proves a property for all inputs, at a higher cost in effort.

History

Testing as a deliberate practice grew with programming in the 1950s and 1960s, but it was informal. In the late 1990s, Kent Beck and Erich Gamma wrote JUnit, a small framework for writing tests in Java, and it set the pattern that most test frameworks since have followed: a test is a method, an assertion checks the result, and a runner reports the failures. Kent Beck's 2002 book on test-driven development made the habit of writing the test before the code widely known. It caught on because it made changes safer, and because automated checks cost less than manual testing each time the code changed.

Recap

  • A unit test calls one small piece of code on chosen inputs and asserts the expected output.
  • The expected value must come from the specification, so a test can catch a bug and not repeat it.
  • A suite of tests runs fast and makes refactoring safe, but it covers only the inputs it tries.
  • Test edges, avoid tests that only copy the code's output, and do not mistake coverage for correctness. Proofs over all inputs are the next step: Formal Verification.

Read next: Formal Verification shows how to prove a property for every input rather than a sample. Related ideas are Immutability, which makes some functions easier to test, and pure functions, whose output depends only on their inputs.

Check yourself

QuestionWhat must be the source of the expected value in a unit test, and what goes wrong if it comes from running the code?Show answer
The expected value must come from the specification, what the function ought to return. If it is taken from running the code, the test only confirms the current behaviour, including any bug, so it cannot catch that bug.
QuestionA function returns the sum of a list plus 2. A test uses the input [1, 2, 3]. What value should the test expect, and what is the result if the code forgets the plus 2?Show answer
The expected value is 1+2+3+2=81 + 2 + 3 + 2 = 8. If the plus 2 is forgotten, the function returns 6, and the assertion fails because 6 does not equal 8.
QuestionWhy can a test suite with 100 percent line coverage still miss a serious bug?Show answer
Coverage only shows which lines ran during the tests. A bug can sit in a branch that runs but is checked with the wrong expected value, or in an input the tests never tried, such as an empty list, so no assertion catches it.
QuestionA team tests a password checker whose rule is at least eight characters with at least one digit. Its ten inputs are all eight-character passwords with letters only. Describe one missing test that makes sense and what it would check.Show answer
A useful missing test uses an input at the edge of the rule, such as a seven-character password, which should be rejected, or a password with a digit and a symbol, which should be accepted. The test checks that the checker gives the rule's answer for that boundary, not only for the typical case.

Sources