Unit Testing Basics for People Who Have Never Written a Test
If you have only ever tested your code by running it and looking at the result, you are not alone. Most beginners start that way. It works until the project grows, and then every change makes you wonder whether something else quietly broke.
Unit tests solve this by turning your checks into code that runs automatically. You write them once, and the computer repeats them in seconds. This guide explains what a unit test is, shows a first example, and gives you habits that make tests worth having.
What a Unit Test Is
A unit test checks one small piece of your program, such as a single function, in isolation. You give it a known input, run the code, and compare the result with the output you expect. If they match, the test passes. If not, it fails and tells you where.
The word "unit" is loose, but it usually means the smallest piece that makes sense to check alone. The key traits are that tests are small, fast, and independent. A good test suite can run in seconds, which means you can run it constantly.
Why Bother
Tests give you several benefits that are hard to get any other way.
- Confidence to change code. If the tests still pass after a change, you have evidence that you did not break existing behavior.
- Faster bug finding. A failing test points to the area that broke, often saving long debugging sessions.
- Living documentation. Tests show how a function is meant to be used, with concrete examples.
- Better design. Code that is hard to test is often tangled. Writing tests nudges you toward smaller, clearer functions.
Tests cost time to write, and they are not a guarantee of correctness. But for any code you plan to keep, they usually pay off.
Your First Test
Suppose you have a small function in a file called shop.py.
def apply_discount(total, percent):
return total - (total * percent / 100)
Python includes a testing tool called unittest, and many people also use a popular third-party tool called pytest. Here is a test written for pytest, which only needs plain functions and the assert keyword.
from shop import apply_discount
def test_ten_percent_discount():
assert apply_discount(200, 10) == 180
def test_zero_discount_changes_nothing():
assert apply_discount(50, 0) == 50
Save this as test_shop.py and run pytest from the project folder. Each function whose name begins with test is run. An assert statement fails the test if the condition is false.
The Shape of a Good Test
Most tests follow the same three steps, often called Arrange, Act, Assert.
- Arrange: set up the input and any needed objects.
- Act: call the code you are checking.
- Assert: confirm the result is what you expected.
Keeping this structure makes tests easy to read. Each test should check one behavior, and its name should describe that behavior. A name like test_zero_discount_changes_nothing explains itself when it fails, while test1 does not.
What to Test
You cannot test everything, so focus on where tests give the most value.
- The normal case. Typical input that should work.
- Edge cases. Empty lists, zero, negative numbers, very large values, and text with unusual characters.
- Error cases. Input that should be rejected, and the error it should raise.
- Past bugs. When you fix a bug, add a test that would have caught it, so it cannot quietly return.
Testing edge cases is where beginners often learn the most. Asking "what happens if the percent is negative?" can reveal that your function needs a rule you had not considered.
Keep Tests Independent
A test should not depend on another test running first, and it should not leave behind changes that affect the next one. If tests share state, a failure in one can cause misleading failures elsewhere, and the order of running becomes important.
Avoid tests that rely on things outside your control, such as the current time, a live network service, or a real database. When your function depends on one of these, replace it in the test with a simple stand-in, often called a mock or a fake. This keeps tests fast and predictable.
Common Beginner Mistakes
- Testing too much at once. A test with ten assertions is hard to diagnose. Split it up.
- Copying the code into the test. If the test just repeats the same calculation as the function, it proves nothing. Use known, independently worked-out expected values.
- Testing the framework. You do not need to test that the language adds numbers correctly. Test your logic.
- Ignoring failing tests. A red test that people tolerate teaches everyone to ignore the whole suite.
- Chasing perfect coverage. Covering every line is not the same as testing the right things. Prioritize important and risky code.
Making Tests a Habit
Run your tests often, ideally after every small change. Many editors can run them with a single shortcut. On a team, set up your project so that tests run automatically before changes are merged.
Some developers write the test before the code, a practice known as test-driven development. It is optional, but trying it on one small function can be eye-opening. You define the behavior first, watch the test fail, then write just enough code to make it pass.
Start small. Pick one function in your current project, write three tests for it, and run them. The first test is the hardest. After that, the habit builds itself.
Frequently Asked Questions
How many tests should I write?
There is no fixed number. Cover the main behavior, the edge cases, and any past bugs for the code that matters. Add tests where a failure would be costly or where code is complicated.
What is the difference between unit tests and integration tests?
Unit tests check small pieces in isolation, while integration tests check that several parts work together, such as your code and a database. Both are useful, and unit tests are usually the larger and faster group.
Do I need a framework to write tests?
You can write basic checks with plain assertions, but a framework such as pytest or unittest makes running, reporting, and organizing tests much easier, so it is worth using one.