What is a unit test?
A unit test checks one small “unit” of code, usually a single function or method, by itself. It gives the function known inputs and checks that it returns the right output or takes the right action.
Because unit tests are small, they run quickly. A large project can have thousands of unit tests that finish in seconds. That speed matters because it lets developers get feedback immediately after they make a change.
Unit tests also act as documentation. If you are unsure how a function is supposed to behave, reading its tests is often the clearest way to find out.
Arrange, act, assert
Most unit tests follow a simple three-step pattern:
For example, if you are testing a grade(score) function, you would arrange a score of 95, act by calling grade(95), and assert the answer is "A".
Isolation and mocking
A unit test should focus on the unit you are testing, not on the rest of the system. If the function you are testing normally reads from a database or calls an external API, the test can replace that dependency with a fake version called a mock.
Mocking lets you control what the dependency returns. If you are testing a function that sends an email, you do not actually send an email in the test. Instead, you mock the email sender and assert that it would have been called with the right address.
Why isolate? When a unit test fails, you want to know exactly which function is broken. If the test depends on a real database, a network hiccup can make a perfectly good test fail, which makes debugging harder.
Coverage is not the goal
Test coverage measures what percentage of your code is run by your tests. It is a useful signal, but it is not the same as quality. A project with 100% coverage can still have terrible tests if the tests never check anything meaningful.
Good tests are about behavior, not lines of code. A single thoughtful test that checks an edge case is more valuable than ten tests that each run the same happy path.
Try the test runner
The function below converts a quiz score into a letter grade. Fill in the Expected column, then click Run tests to see if each case passes.
def grade(score): if score >= 90: return "A" if score >= 80: return "B" if score >= 70: return "C" if score >= 60: return "D" return "F"
Test cases
grade(95)grade(82)grade(76)grade(59)grade(89)Quick quiz
1. What is the smallest part of the system a unit test usually checks?
2. In arrange-act-assert, what happens during “assert”?
3. Why do unit tests use mocks?
Keep learning
Unit tests check small parts. Next, learn how integration and system tests check that those parts work together.
Part of the “Testing, QA, and CI” series.