1. Home
  2. Blog
  3. Test Automation

Test Automation

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.

9 min read
Python unittest tutorial with assert methods, setUp, subTest and mocks

Key takeaways

  • Python unittest ships with Python, so it needs no install. Tests are methods whose names start with test inside a unittest.TestCase class.
  • Use the specific assert methods, such as assertEqual, assertIn and assertRaises, because their failure messages show exactly what differed.
  • setUp runs 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_total runs a single test.
  • python -m unittest discover -s tests -p "test_*.py" finds tests in a folder.
  • python -m unittest -f stops at the first failure, and -k total runs 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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
Software Development

URL Encoding Explained: Spaces, Plus Signs and UTF-8

URL encoding explained with tested Python and JavaScript code: percent encoding, reserved characters, %20 vs plus, UTF-8 bytes, encodeURI vs…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Software Testing

State Transition Testing: Diagram, Table and Example

State transition testing explained with a login lockout example: states, events, the diagram, the state table, valid and invalid transitions,…

Read article →
Databases & SQL

Second Highest Salary in SQL: 5 Tested Ways and the Tie Trap

Find the second highest salary in SQL five ways: MAX subquery, LIMIT OFFSET, DENSE_RANK, a correlated subquery and per department,…

Read article →
Databases & SQL

SQL ROW_NUMBER: Top N per Group, Dedupe and Pagination

SQL ROW_NUMBER explained with tested queries: PARTITION BY, top N per group, deleting duplicates, pagination, the tie trap and how…

Read article →
Software Development

JavaScript Set: Union, Intersection and Removing Duplicates

JavaScript Set explained with tested examples: add, has, delete, deduplicating arrays, the new union and intersection methods, equality rules and…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →
Software Development

Python Map and Filter: Examples vs List Comprehensions

Python map and filter explained with tested examples: lazy map objects, multiple iterables, filter(None), chaining, and a timed comparison with…

Read article →
Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
Software Development

Unix Timestamp Explained: Seconds vs ms

A Unix timestamp counts seconds since 1 January 1970 UTC. Learn seconds vs milliseconds, converting in Python, JavaScript and SQL,…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Software Development

JavaScript Date: Format, Parse, Timezone Bugs

JavaScript Date explained with tested Node.js code: zero-based months, the date-only UTC parsing trap, toISOString, getTimezoneOffset, Intl formatting, date math…

Read article →
Software Development

Python Requests: GET, POST, Timeouts, Retries

Python requests explained with code tested against a local API: GET with params, POST json vs data, headers and auth,…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Databases & SQL

SQL LAG and LEAD: Compare Rows, 5 Examples

SQL LAG and LEAD read values from the previous or next row without a self join. Five tested examples: change,…

Read article →
Databases & SQL

SQL STRING_AGG: Combine Rows Into One String

SQL STRING_AGG joins values from many rows into one string per group. See syntax for PostgreSQL, SQL Server, MySQL GROUP_CONCAT,…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →