Learn unittest

Python's built-in xUnit-style testing framework, with mocking included

13 lessons · 2 hours · 4 levels · covers unittest Python 3.13

unittest is the testing framework that ships with Python: test case classes, rich assertions, fixtures, test discovery and a runner, plus unittest.mock for replacing dependencies. It needs no installation, CPython itself is tested with it, and pytest runs unittest tests unchanged. Learning it gives you dependable tests anywhere Python runs.

Before you start

unittest builds on these; the tree links to the exact lessons you need.

How deep do you want to go?

1. EssentialsRead and write simple code, do the everyday basics4 lessons · 35 min in total
2. PracticalUse it productively at work, with the usual idioms7 lessons · 1 hour in total
3. AdvancedThe less common features, performance and trade-offs10 lessons · 2 hours in total
4. ExpertInternals and the edge cases experts know13 lessons · 2 hours in total

The unittest tree

unittestYour first TestCaseYour first TestCaseAssertion methodsAssertion methodsTesting exceptions, warnings and logsTesting exceptions,warnings and logsRunning tests and discoveryRunning tests anddiscoverysetUp, tearDown and cleanupssetUp, tearDown andcleanupsParametrised tests with subTestParametrised testswith subTestSkipping tests and expected failuresSkipping tests andexpected failuresDefining functionsDefining functionsClasses and instancesClasses andinstancesExceptions in depthExceptions in depthContext managers and withContext managersand with
Essentials and Practical shown (7 of 13 lessons); the full list is below. Click a lesson to read it.

All 13 lessons, in order

Writing and running tests

  1. Your first TestCase · Essentials · 9 min

    Write tests as methods named test_* on a unittest.TestCase subclass and run them with unittest.main().

  2. Assertion methods · Essentials · 9 min

    Pick the most specific assert method so failures explain themselves, including assertAlmostEqual and assertCountEqual.

  3. Testing exceptions, warnings and logs · Essentials · 9 min

    Check that code raises the right exception with assertRaises, and verify warnings and log output.

  4. Running tests and discovery · Essentials · 8 min

    Run tests with python -m unittest, use discovery, select tests by name, and read the output.

Fixtures and test organisation

  1. setUp, tearDown and cleanups · Practical · 11 min

    Share setup across tests with setUp and setUpClass, and release resources reliably with addCleanup and enterContext.

  2. Parametrised tests with subTest · Practical · 8 min

    Test many inputs in one method with self.subTest so each failing case is reported separately.

  3. Skipping tests and expected failures · Practical · 7 min

    Skip tests conditionally with skipIf and skipUnless, and mark known bugs with expectedFailure.

Mocking

  1. Mock objects · Advanced · 12 min

    Replace collaborators with Mock and MagicMock, configure return_value and side_effect, and assert on calls.

  2. patch: replacing dependencies · Advanced · 13 min

    Temporarily replace objects with mock.patch as a decorator or context manager, and learn where to patch.

  3. Testing async code · Advanced · 10 min

    Test coroutines with IsolatedAsyncioTestCase and mock async dependencies with AsyncMock.

Framework internals and tooling

  1. Specs and autospec · Expert · 12 min

    Make mocks enforce real signatures and attributes with spec, autospec, create_autospec and seal.

  2. Loaders, suites, runners and results · Expert · 12 min

    Understand TestLoader, TestSuite, TextTestRunner and TestResult, and customise collection with load_tests.

  3. Custom equality, diffs and pytest interop · Expert · 10 min

    Tune failure output with maxDiff and longMessage, register type-specific equality, and run unittest suites under pytest.