Python Unittest: Assert Methods, setUp, subTest and Mocks, Tested
Python unittest is the testing framework built into the standard library. Learn how to write a TestCase, pick the right assert method, share setup with setUp, loop with subTest, skip tests and mock dependencies, using a suite we ran.
- Python unittest ships with Python, so it needs no install. Tests are methods whose names start with
testinside aunittest.TestCaseclass. - Use the specific assert methods, such as
assertEqual,assertInandassertRaises, because their failure messages show exactly what differed. setUpruns before every test, so each test starts from a fresh object.- Our 9-test suite ran in 0.003 seconds with 1 skip and 1 expected failure, and pytest ran the same file unchanged.
Every Python install already contains a complete testing framework. Python unittest gives you test classes, a rich set of assertions, setup and teardown hooks, test discovery and a mocking library, all without adding a dependency. Many older codebases and the Python standard library itself are tested with it, so knowing it pays off even if you prefer pytest for new projects.
In this tutorial we build a small shopping cart and test it step by step. Every result shown came from running the suite with Python 3.13.6 on Windows. File paths in tracebacks are shortened.
What is unittest?
The unittest module follows the xUnit style that started with JUnit in Java. You group related tests in a class that inherits from unittest.TestCase. Each method that starts with test is one test. A test runner finds those methods, runs each one in isolation, and reports a pass, failure, error or skip for each. A failure means an assertion did not hold; an error means the test crashed with some other exception.
If you are still deciding what deserves a unit test, our guide to unit testing vs integration testing explains where each type fits.
The code under test
Our example is a tiny cart in cart.py. It rejects negative prices and quantities below 1, merges repeated items, and applies a percentage discount:
class Cart:
def __init__(self):
self.items = {}
def add(self, name, price, qty=1):
if price < 0:
raise ValueError("price must be >= 0")
if qty < 1:
raise ValueError("qty must be >= 1")
old = self.items.get(name, (price, 0))
self.items[name] = (price, old[1] + qty)
def total(self, discount=0):
gross = sum(p * q for p, q in self.items.values())
return round(gross * (1 - discount / 100), 2)
Your first TestCase
Create test_cart.py next to it. The file name starting with test matters, because discovery looks for test*.py by default:
import unittest
from cart import Cart
class CartTest(unittest.TestCase):
def setUp(self):
self.cart = Cart()
self.cart.add("pen", 1.5, 2)
def test_total(self):
self.assertEqual(self.cart.total(), 3.0)
def test_add_same_item_increases_qty(self):
self.cart.add("pen", 1.5)
self.assertEqual(self.cart.items["pen"], (1.5, 3))
if __name__ == "__main__":
unittest.main()
The if __name__ == "__main__" block lets you run the file directly with python test_cart.py. We will add more tests to this class in the sections below.
The assert methods you will actually use
TestCase provides many assert methods instead of the plain assert statement. The reason is the report: when assertEqual fails, it prints both values and, for lists and dictionaries, a diff of what changed.
| Method | Checks | Typical use |
|---|---|---|
assertEqual(a, b) |
a == b |
Return values, totals |
assertNotEqual(a, b) |
a != b |
Generated IDs differ |
assertTrue(x) / assertFalse(x) |
truthiness | Flags and checks |
assertIs(a, b) / assertIsNone(x) |
identity, None |
Singletons, missing values |
assertIn(a, b) |
a in b |
Keys, list members, substrings |
assertIsInstance(a, T) |
type | Factory results |
assertAlmostEqual(a, b, places=7) |
rounded difference is 0 | Floats and money |
assertCountEqual(a, b) |
same items, any order | Unordered results |
assertRaises(Exc) |
exception is raised | Validation errors |
Here is how several of them look in our suite:
def test_discount_float(self):
self.cart.add("book", 10.1)
self.assertAlmostEqual(self.cart.total(discount=10), 11.79, places=2)
def test_contents(self):
self.assertIn("pen", self.cart.items)
self.assertIsInstance(self.cart.items, dict)
self.assertCountEqual(list(self.cart.items), ["pen"])
Every assert method also accepts an optional msg argument, which is added to the failure output. Use it when the values alone would not tell a reader what went wrong.
Tip: never compare floats with assertEqual. Use assertAlmostEqual with places or delta, because values like 0.1 + 0.2 are not exactly 0.3 in binary.
Testing exceptions
Use assertRaises as a context manager. The as ctx part captures the exception so you can check its message too:
def test_negative_price_rejected(self):
with self.assertRaises(ValueError) as ctx:
self.cart.add("bad", -1)
self.assertIn("price", str(ctx.exception))
Checking the message matters. Without it, the test would still pass if the code raised a ValueError for some unrelated reason. assertRaisesRegex combines both checks in one call.
setUp, tearDown and class-level setup
The runner calls setUp before each test method and tearDown after it, even when the test fails, as long as setUp itself succeeded. That gives every test a fresh cart, so one test adding items can never break another.
@classmethod
def setUpClass(cls):
cls.tax_rate = 18 # runs once for the whole class
def setUp(self):
self.cart = Cart() # runs before every test
self.cart.add("pen", 1.5, 2)
def tearDown(self):
self.cart = None # runs after every test
Use setUpClass and tearDownClass only for expensive, read-only resources, such as loading a large reference file. Shared mutable state at class level is a common cause of tests that pass alone but fail together, a problem covered in our flaky tests guide. For cleanup that must happen even if setUp fails halfway, register it with self.addCleanup(func).
Looping over inputs with subTest
When you want to test several inputs with the same logic, a plain loop stops at the first failure. subTest reports each case separately and keeps going:
def test_qty_rules(self):
for qty, ok in [(1, True), (0, False), (-2, False)]:
with self.subTest(qty=qty):
if ok:
self.cart.add("x", 1, qty)
else:
self.assertRaises(ValueError, self.cart.add, "x", 1, qty)
To prove it keeps going, we ran a separate test that checks 2, 3 and 4 are even. Only 3 failed, and the report named the exact case, (n=3), while 4 was still checked. Choosing good input values for these loops is a skill of its own; boundary value analysis is the quickest way to pick them.
Skips and expected failures
Sometimes a test cannot run yet, or documents a known bug. Decorators make that visible in the report instead of hiding it in comments:
@unittest.skip("payment API not ready")
def test_checkout(self):
pass
@unittest.expectedFailure
def test_known_rounding_bug(self):
self.assertEqual(0.1 + 0.2, 0.3)
There are also skipIf and skipUnless, for example to skip a test on Windows. An expected failure that suddenly passes is reported as an unexpected success, which tells you the bug was fixed and the decorator can go.
Mocking dependencies with unittest.mock
Real carts look prices up from a service. In a unit test you replace that service with a Mock, set its return value, and then check how it was called:
from unittest import mock
def test_mock_price_lookup(self):
api = mock.Mock()
api.price.return_value = 9.99
self.cart.add("mug", api.price("mug"))
api.price.assert_called_once_with("mug")
self.assertEqual(self.cart.total(), 12.99)
For code that imports a dependency itself, use mock.patch as a decorator or context manager to swap it out. Our Python mocking guide covers patch, side_effect and the classic “patch where it is used” rule, and test doubles explains when a mock is the wrong tool.
Running the tests
From the folder that holds both files, run the module with verbose output:
python -m unittest -v
test_add_same_item_increases_qty (test_cart.CartTest.test_add_same_item_increases_qty) ... ok
test_checkout (test_cart.CartTest.test_checkout) ... skipped 'payment API not ready'
test_contents (test_cart.CartTest.test_contents) ... ok
test_discount_float (test_cart.CartTest.test_discount_float) ... ok
test_known_rounding_bug (test_cart.CartTest.test_known_rounding_bug) ... expected failure
test_mock_price_lookup (test_cart.CartTest.test_mock_price_lookup) ... ok
test_negative_price_rejected (test_cart.CartTest.test_negative_price_rejected) ... ok
test_qty_rules (test_cart.CartTest.test_qty_rules) ... ok
test_total (test_cart.CartTest.test_total) ... ok
----------------------------------------------------------------------
Ran 9 tests in 0.003s
OK (skipped=1, expected failures=1)
Note that tests run in alphabetical order of method name, not the order you wrote them. Other useful commands:
python -m unittest test_cart.CartTest.test_totalruns a single test.python -m unittest discover -s tests -p "test_*.py"finds tests in a folder.python -m unittest -fstops at the first failure, and-k totalruns only tests whose names match.
The exit code is 0 when everything passes and 1 when anything fails, which is what a CI pipeline needs.
Reading a failure
We wrote a deliberately failing test that compares [1, 2, 3] with [1, 2, 4]. The output pinpoints the difference:
FAIL: test_list (test_fail.T.test_list)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_fail.py", line 4, in test_list
self.assertEqual([1, 2, 3], [1, 2, 4])
AssertionError: Lists differ: [1, 2, 3] != [1, 2, 4]
First differing element 2:
3
4
It names the index of the first difference and shows a diff underneath. A bare assert a == b inside unittest would only say AssertionError, which is why the assert methods exist.
Unittest vs pytest
| Aspect | unittest | pytest |
|---|---|---|
| Install | Built in | pip install pytest |
| Test style | Classes and assert methods | Plain functions and assert |
| Setup | setUp, setUpClass |
Fixtures with scopes |
| Many inputs | subTest |
@pytest.mark.parametrize |
| Plugins | Few | Large ecosystem |
You do not have to choose forever. We ran pytest test_cart.py (pytest 9.2.0) on the same unchanged file and it collected and ran the unittest tests, so a team can switch runners first and rewrite tests gradually. Our pytest tutorial and pytest fixtures guide show the other side.
Good habits for unittest suites
- Name tests after the behaviour, such as
test_negative_price_rejected, so the report reads like a specification. - Keep one behaviour per test. Several asserts are fine if they check the same behaviour.
- Keep tests independent; never rely on one test running before another.
- Mock slow or external things such as networks, clocks and payment APIs, but not your own simple logic.
- Run the suite in CI on every push and measure what it covers; see our code coverage guide.
Final thoughts
Python unittest gives you everything a solid test suite needs without a single install: TestCase classes, precise assert methods, setUp and tearDown, subTest loops, skips and a full mocking library. Start with a few tests around the code you change most, run them with python -m unittest -v, and wire the command into CI. If you later move to pytest, your unittest tests keep running unchanged.
Frequently asked questions
Do I need to install unittest in Python?
No. The unittest module is part of the Python standard library, so it is available in every normal Python install without pip.
What is the difference between setUp and setUpClass?
setUp runs before every single test method, while setUpClass is a class method that runs once before all tests in the class. Use setUp for fresh state and setUpClass for expensive read-only resources.
How do I run a single unittest test?
Pass its full dotted name to the runner, for example python -m unittest test_cart.CartTest.test_total, or use the -k option to match part of a test name.
Why use assertEqual instead of assert?
assertEqual prints both values and a diff for lists and dictionaries when it fails, and the runner records it as a failure in the report. A bare assert gives far less detail.
Can pytest run unittest tests?
Yes. pytest collects unittest.TestCase classes automatically. We ran our unchanged unittest file with pytest and every test ran, so you can switch runners before rewriting tests.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.