What Is Unit Testing, and How Do You Write a Good Test?
Unit testing checks the smallest parts of your code, one function at a time, so bugs are caught where they start. Learn what makes a good test and how to write one.
On this page
Short answer
Unit testing is the practice of testing the smallest pieces of code, usually one function or method at a time, in isolation from the rest of the system. Each test checks that a piece of code returns the expected result for a given input. Good tests are fast, repeatable and focused, so a failing test points straight at the broken code.
What is unit testing?
Unit testing is the practice of testing the smallest pieces of a program, usually one function or method at a time, in isolation from the rest of the system. A unit test calls the function with a known input and checks that the output matches what was expected.
The point is to catch bugs where they start. When a test fails, the cause is inside that one function, not somewhere across the whole system. That narrow focus is what makes unit tests fast to write, fast to run and easy to read.
Tests are code too. They live next to the code they check, they run in a test runner, and they run automatically whenever the code changes. A team that runs its tests on every change learns about breakage within minutes, not weeks. If you are building the product itself, custom software development work usually includes the test suite as part of the delivery, not as an afterthought.
What makes a good unit test?
A good unit test checks one behaviour and has a clear name that states what it checks. When it fails, the name alone should tell the reader what broke, without opening the test file.
A test worth keeping has four qualities:
- Independent. It runs on its own, and the result does not depend on the order tests run in.
- Fast. The whole suite runs in seconds or minutes, so the team actually runs it.
- Repeatable. It gives the same result every time, with no dependence on the time of day, the network or random data.
- Focused. It checks one behaviour, so a failure has one cause.
A test that checks five things at once is hard to trust. When it fails, nobody knows which of the five broke, and fixing it means guessing. Small, single-purpose tests cost more lines to write and far less time to debug.
Good tests also survive change. A test tied to the exact internal shape of the code breaks whenever the code is refactored, even when the behaviour is unchanged. A test written against the public behaviour keeps passing through a refactor, which is the whole point: it should catch changes in behaviour, not changes in structure.
How do you write a unit test?
You write a unit test by following the same three steps every time: set up the input, call the code, and check the result. That shape keeps tests short and easy to read.
- Arrange. Create the inputs and any objects the function needs.
- Act. Call the function once, with those inputs.
- Assert. Check the result against the value you expected.
Name the test after the behaviour it checks, for example 'discount_applies_to_orders_over_100'. A name like 'test_3' tells the next reader nothing. When the suite is green, names do not matter much; when it is red, names are the first thing anyone reads.
What should you test, and what should you skip?
You should test the code where a wrong result would hurt: calculations, rules, branching logic and anything that handles money, dates or permissions. You can skip code with no logic of its own, such as simple getters or framework boilerplate.
| Area | Test it | Why |
|---|---|---|
| Calculations and rules | Yes | Wrong results reach users directly |
| Branching logic | Yes | Each branch can hide a bug |
| Money, dates, permissions | Yes | Mistakes are costly and hard to spot |
| Simple getters and setters | No | No logic to get wrong |
| Framework boilerplate | No | The framework already tests it |
Coverage targets can mislead. A suite that runs 90% of the lines can still miss the one branch that matters. Aim for the risky logic first, then let coverage follow, not the other way round.
Example (hypothetical): testing a discount calculation
Example (hypothetical): a shop gives a 10% discount on orders over 100. The function takes an order total and returns the price to charge. Three tests cover the rule.
A 90 order returns 90, because it is below the threshold. A 120 order returns 108, because 10% of 120 is 12 and 120 minus 12 is 108. A 100 order returns 100, because the rule applies only above 100, so the boundary case matters as much as the others.
The three tests together pin down the rule: below, above and exactly on the boundary. If someone later changes the threshold to 150, the 120 test fails at once and shows the rule changed. That is the whole point of the test: it guards the rule, not just the code.
What are the common mistakes?
The most common mistakes are testing too much at once, depending on outside systems, and writing tests that are hard to read.
- Testing through the database or network. A unit test should not need either; a slow suite nobody runs is worse than a small suite that runs every time.
- Asserting too much. One test, one behaviour; when it fails, the cause should be obvious.
- Copying production code into tests. If the test repeats the logic, it will repeat the bug.
- Skipping the boundary. Most bugs live at edges: zero, one, empty, exactly at the limit.
How do you fit unit tests into a team workflow?
You fit unit tests into a team workflow by running them automatically on every change, so no code reaches review without its tests passing.
- Write the test with the code, not after it, while the behaviour is still fresh.
- Run the suite locally before pushing, so failures are yours to fix first.
- Run it again in continuous integration on every pull request.
- Block merging while tests fail, so a red suite cannot quietly reach production.
- Review tests like production code, because they are.
Teams that treat tests as part of the change, not an extra chore, end up with suites they trust. For a wider view of how testing fits into delivery, see the guide to white box testing.
When a test fails in the pipeline, treat it as a stop signal, not as background noise. The team that fixes a failing test the same day keeps the suite trustworthy; the team that lets failures pile up ends up ignoring the suite entirely, and then the tests are just decoration.
Automating the pipeline around the tests matters as much as the tests themselves, which is where DevOps services come in: the build, the test run and the deploy all happen on every change.
Key takeaways
- Unit testing checks one function at a time, in isolation, so a failure points at the cause
- A good test is independent, fast, repeatable and focused on one behaviour
- Test the risky logic first: calculations, rules, branches, money and permissions
- Boundary cases matter most: zero, one, empty and exactly at the limit
- Run the suite automatically on every change and fix failures at once
Frequently asked questions
How many unit tests should a function have?
As many as its behaviours need. A simple function may need one test; a function with several branches needs one test per branch, plus tests for the boundaries. Count behaviours, not lines, and add a test whenever a new rule or edge case appears.
Do unit tests replace manual testing?
No. Unit tests check that small pieces behave as designed, but they cannot tell you whether the product is usable or whether the design is right. Manual testing, integration tests and real user feedback still matter. Unit tests catch regressions early; they do not replace checking the whole product.
What is the difference between unit testing and integration testing?
Unit testing checks one piece of code in isolation, with its dependencies replaced by stand-ins. Integration testing checks that several pieces work together, such as code talking to a database or an API. Both are needed: unit tests find logic bugs fast, while integration tests find wiring problems.
Should I test private functions directly?
Usually not. Test them through the public functions that use them, since that is how the code is actually used. If a private function is so complex that it needs its own tests, that is often a sign it should become a separate, testable piece of code.
How do I start unit testing an old codebase?
Start with the riskiest code: the parts that change often and the parts where a bug would hurt most. Add tests for new code first, then add tests to old code whenever you fix a bug there, starting with a test that reproduces the bug. The suite grows with each change.
Can unit tests slow a team down?
They slow the first change and speed up every change after it. Writing tests takes time, but the team saves that time many times over by catching regressions in minutes instead of finding them in production. A suite that runs in seconds is cheap insurance against a bad release.