For developers
What are unit tests, and how do you write your first one?
Unit tests check small pieces of code automatically so you can change things without fear. Learn how they work, what to test, and how to write a first test in Python.

Unit tests are small automated checks that run a single piece of code, such as one function, with known inputs and confirm it produces the expected output. They run in seconds, and they let you change code with confidence, because if you break something, a test tells you straight away.
This guide explains what unit tests are, how they differ from other kinds of tests, what is worth testing, how to write a first test in Python, and the habits that keep a test suite useful.
What exactly is a unit test?
A 'unit' is the smallest piece of code that makes sense to test on its own, usually a function or a method. A unit test calls that function with specific inputs and checks the result with an assertion, a statement such as 'the result should equal 42'. If the assertion is true, the test passes. If not, it fails and reports what it expected and what it got.
Most unit tests follow the same three-step shape, often called Arrange, Act, Assert: set up the input, run the code, check the result. Keeping to that shape makes tests short and easy to read.
Unit tests should be fast and independent. They do not talk to real databases, networks or file systems, and they do not depend on each other or on the order they run in. That is what lets you run hundreds of them every time you save a file.
How do unit tests differ from other tests?
Unit tests are one layer of testing. A common model, the test pyramid, suggests many fast unit tests at the bottom, fewer integration tests in the middle and a small number of slow end-to-end tests at the top.
- Unit tests: one function or class in isolation. Fast, precise, many of them.
- Integration tests: several parts working together, such as code plus a real database.
- End-to-end tests: the whole application driven like a user would, often through a browser.
- Manual testing: a person trying the feature, still valuable for new or visual work.
If you break something, a test tells you straight away.
How do you write your first unit test?
Here is a small example in Python using pytest, a widely used open-source testing tool. Suppose you have a function in a file called prices.py that applies a discount: def apply_discount(price, percent): return round(price * (1 - percent / 100), 2).
In a file called test_prices.py, write a test function whose name starts with test_: def test_apply_discount(): assert apply_discount(100, 20) == 80. Run pytest in the terminal from the project folder. It finds files and functions starting with test_, runs them and reports passes and failures.
Then add tests for edge cases: a discount of zero, a discount of 100, a price with pennies. Python's standard library also includes the unittest module if you prefer not to install anything. Other languages have equivalents, such as JUnit for Java and several test runners for JavaScript.
What should you test?
You cannot test every possible input, so focus where bugs are likely or costly. Good candidates:
- Business rules and calculations: prices, dates, permissions, validation.
- Edge cases: empty lists, zero, negative numbers, very large values, missing fields.
- Error handling: does the function raise the right error for bad input?
- Bugs you have fixed: write a test that reproduces the bug before fixing it, so it never comes back.
- Code you are about to refactor, so you know behaviour stayed the same.
What are mocks and when should you use them?
Sometimes the code you want to test calls something slow or unpredictable, such as a web API, the current time or a database. A mock, or test double, is a stand-in that returns fixed answers, so your unit test stays fast and repeatable. Python's standard library includes unittest.mock for this.
Use mocks sparingly. A test that mocks everything ends up testing the mocks rather than your code, and it breaks whenever the internals change. A good alternative is to structure code so that the core logic is a plain function that takes data in and returns data out, with the slow parts at the edges. Pure functions like that are easy to test without mocks.
What habits keep tests useful?
A test suite is only valuable if people trust it and run it. Flaky tests that fail at random, and slow suites that take minutes, quickly get ignored. Keep unit tests fast, deterministic and focused on behaviour, not on how the code happens to be written inside.
Name tests after the behaviour they check, such as test_discount_cannot_make_price_negative, so a failure explains itself. Run the tests automatically on every change, ideally in a continuous integration pipeline, so nothing merges with failing tests.
Some developers write the test before the code, a practice called test-driven development (TDD): write a failing test, write just enough code to pass, then tidy up. It is not required, but it is a good way to think through what a function should do before writing it.
Frequently asked questions
What is the difference between unit tests and integration tests?
+
Unit tests check a single piece of code in isolation, with no real database or network. Integration tests check that several parts work together, such as your code and a real database. Both are useful.
What is test coverage, and what percentage should I aim for?
+
Coverage measures which lines of code run during your tests. It shows untested areas, but high coverage does not prove the tests check the right things. Focus on testing important behaviour rather than chasing a number.
Do unit tests slow down development?
+
They take time to write, but they usually save more by catching bugs early and making changes safer. The payoff grows as a project gets larger and lives longer.
What is test-driven development?
+
TDD is a practice where you write a failing test first, then write the code to make it pass, then refactor. It encourages small, well-defined functions and keeps tests in step with the code.
Should beginners write unit tests?
+
Yes, once you can write basic functions. Testing a few functions in a small project teaches you to think about inputs, outputs and edge cases, which improves your code even without a large test suite.
What is a flaky test?
+
A flaky test passes sometimes and fails other times without any code change, often because it depends on timing, order, randomness or an external service. Fix or remove flaky tests quickly, because they erode trust in the whole suite.
Pick one function in a current project, write three tests for it including an edge case, and run them. Once you have felt a test catch a mistake you just made, you will want them everywhere.
How we research: Guides are written from established sources and checked for accuracy. They are general information, not professional advice.
Written by
Cursorlane Editorial Team
Software & tools
Our writers are developers and heavy software users who test what they write about and update guides when the tools change.


