Programming & syntax · reviewed in July 2026
Unit test
A unit test is a piece of code that automatically checks a small function or method behaves as expected, given a known set of inputs. It runs repeatably and in isolation, without depending on a real database or external services.
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5Frequently asked questions
What's the difference between a unit test and an integration test?
A unit test checks a single piece of code in isolation, usually mocking its dependencies. An integration test checks that several pieces work correctly together, including real components like a database.
What do you write unit tests with in Python?
pytest is the most widely used framework: it lets you write plain test_* functions with assert statements, with no need to inherit from a special class.
Why do unit tests matter?
They catch bugs as soon as they're introduced, document how code is supposed to behave, and give you the confidence to change or refactor without breaking anything.