Unit testing
How one small function gets its own test: set up an input, call the function, compare the answer. Then what happens when someone breaks it, and why such tests are fast.
In 30 seconds
A unit test is a few lines of code that check one small piece of a program, usually a single function, on its own.
It follows three moves: arrange an input, act by calling the function, assert that the result equals the answer you worked out beforehand.
Because it touches no database or network, it runs in milliseconds. A team keeps hundreds of them and runs them after every change, so a mistake shows up within seconds, pointing at the piece that broke.
Unit testing, step by step
People draw the line around a “unit” differently: one function, one class, or a few that work closely together. The test syntax shown is that of Jest and Vitest; other tools differ in spelling, not in idea.
- Step 1: One piece, on its own. A program is built from many small parts. A unit test picks one of them, here a function called discount(), and checks it alone, with the rest of the application left out of the picture.
- Step 2: The unit under test. The function has one rule: an order of 100 or more gets 10 off, a smaller one is left alone. Because its output depends only on its input, we can say in advance what the right answer is for any total.
- Step 3: Arrange, act, assert. A unit test is a short piece of code in three parts. Arrange sets up the input, act calls the unit once, and assert compares what came back with the answer worked out beforehand.
- Step 4: Run it. A test runner executes the test. The unit receives 120 and returns 110, the assert finds it equal to the expected 110, and the test passes. It took a couple of milliseconds.
- Step 5: A test catches a slip. Later someone edits the function and types > where >= was. Two tests still pass, but the one for an order of exactly 100 fails: it expected 90 and got 100. Tests at the edges of a rule catch this kind of mistake.
- Step 6: Isolated, so fast. A unit test touches no database, network or clock; if the unit needs one, the test hands it a simple stand-in. With nothing slow or unpredictable involved, hundreds of tests finish in seconds and can run after every change.
- Step 7: What makes a good test. Good unit tests are fast, independent of each other, and give the same result on every run. Each one checks a single behaviour and is named for it. They test what the unit does, not how it is written inside, so they survive a rewrite.
Try it yourself
Learn this first
Nothing. This concept starts from scratch.
Learn next
- Mocks, stubs and fakesThree kinds of stand-in for a test, and what each one checks. Intermediate
- Integration vs end-to-end testingTesting the joins between parts, then the whole system, and what each one costs. Beginner
- Test-driven developmentFailing test, passing code, tidy-up: a leap-year function grown in small rounds. Beginner
Spotted a mistake on this page?