unittest — unit testing framework

unittest assertions, test lifecycle hooks, and a modest unittest.mock example that does not stand in for an external service.

模块页正文目前为英文。

unittest is the standard-library unit-testing framework. Tests are methods on a subclass of TestCase whose names start with test. Assertions such as assertEqual and assertRaises record failures on a TestResult rather than using a bare assert statement. This page runs tests with TestResult directly so the printed summary has no elapsed time. TextTestRunner would add a duration that is not stable.

The lifecycle is setUpClass, then setUp, the test method, and tearDown for each test, then tearDownClass. unittest.mock is in scope here only as a local collaborator: a Mock with a return_value, not a patch of a network client or a fake remote service.

Examples were run against Python 3.13.12. Links point to the Python 3.13 documentation.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

Assertions and the test lifecycle

assertEqual compares two values. assertTrue checks a boolean. assertRaises is used as a context manager around code that must raise a given exception. The loader collects test_equal and test_raises; the default order is the method name, so test_equal runs first.

The printed event list is the lifecycle for this class: setUpClass once, setUp and tearDown around each test, then tearDownClass. Failures and errors stay at zero in this example, which is why wasSuccessful is True.

TestCase.assertEqual, assertRaises, setUp, and tearDown

assertEqual(first, second, msg=None)
assertTrue(expr, msg=None)
assertRaises(expected_exception, *args, **kwargs)
setUp()
tearDown()
setUpClass()
tearDownClass()

Run two tests through TestResult and print the hook order. The tests pass, so failures and errors are both zero.

ParameterDescription
first, secondValues compared by assertEqual. A mismatch is a test failure, not an uncaught exception.
expected_exceptionThe exception type that the code inside the assertRaises context must raise.

Returns: Assertion methods return None on success. TestResult.wasSuccessful() is True when failures and errors are empty. testsRun is the number of test methods that ran.

Raises

  • AssertionError — A failed assertion is recorded as a failure on the result, not printed as a traceback in this example.
  • The signatures above are TestCase methods as documented for Python 3.13. setUpClass and tearDownClass are class methods.
  • This example does not use TextTestRunner, because that runner prints a timing line that can vary.
python
import unittest

events = []

class ArithmeticTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        events.append("setUpClass")

    @classmethod
    def tearDownClass(cls):
        events.append("tearDownClass")

    def setUp(self):
        events.append("setUp")
        self.value = 2

    def tearDown(self):
        events.append("tearDown")

    def test_equal(self):
        events.append("test_equal")
        self.assertEqual(self.value * 2, 4)
        self.assertTrue(self.value > 0)

    def test_raises(self):
        events.append("test_raises")
        with self.assertRaises(ValueError):
            int("x")

suite = unittest.defaultTestLoader.loadTestsFromTestCase(ArithmeticTest)
result = unittest.TestResult()
suite.run(result)
print(result.wasSuccessful(), result.testsRun, len(result.failures), len(result.errors))
print(events)

Expected output

True 2 0 0
['setUpClass', 'setUp', 'test_equal', 'tearDown', 'setUp', 'test_raises', 'tearDown', 'tearDownClass']

Official documentation →

Mock as a local collaborator

unittest.mock.Mock can stand in for an object your code calls. The example gives fetch a fixed return_value and then checks the argument and call_count. That is enough to test Client.label without inventing a server, patching urllib, or reading a token. A Mock is not an authorization mechanism, and this page does not use it to impersonate a public API.

unittest.mock.Mock

Mock(spec=None, side_effect=None, return_value=DEFAULT, ...)
Mock.assert_called_once_with(*args, **kwargs)

Return a canned payload from a Mock collaborator and assert it was called once with a fixed id.

ParameterDescription
return_valueThe value used whenever the mock is called. Here it is a small dict, not a network response.
*argsThe positional arguments expected by assert_called_once_with.

Returns: Calling the mock returns return_value. call_count is the number of calls so far.

Raises

  • AssertionError — Raised by assert_called_once_with if the mock was not called exactly once with those arguments.
  • The signature of Mock has more optional arguments than are shown here; this example only uses return_value and the call assertion.
python
import unittest
from unittest.mock import Mock

class Client:
    def __init__(self, service):
        self.service = service

    def label(self, item_id):
        payload = self.service.fetch(item_id)
        return payload["name"]

class ClientTest(unittest.TestCase):
    def test_label(self):
        service = Mock()
        service.fetch.return_value = {"name": "alpha"}
        client = Client(service)
        self.assertEqual(client.label("item-1"), "alpha")
        service.fetch.assert_called_once_with("item-1")
        self.assertEqual(service.fetch.call_count, 1)

suite = unittest.defaultTestLoader.loadTestsFromTestCase(ClientTest)
result = unittest.TestResult()
suite.run(result)
print(result.wasSuccessful(), result.testsRun, len(result.failures), len(result.errors))

Expected output

True 1 0 0

Related: Official unittest.mock

Official documentation →