Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

assertEqual in unittest: compare actual and expected values

Use `assertEqual` to compare actual and expected values, prepare test data with `setUp`, and cover multiple inputs and exceptions in `unittest`.

Version: Python 3.12

Syntax

self.assertEqual(actual, expected, msg=None)

with self.subTest(label=value):
    self.assertEqual(actual, expected)

In Python 3.12, assertEqual is a method on unittest.TestCase. Call self.assertEqual(actual, expected) with the result first and the expected value second. It checks equality (==), not identity (is). Unequal values cause an assertion failure; use the optional msg to add context.

When both operands have exactly the same type, assertEqual can use a type-specific comparison to give a more informative failure message. This applies to list, tuple, dict, set, frozenset, str, and types registered with addTypeEqualityFunc(). Matching types are not a requirement for equality.

setUp() prepares the test data before each test method, not before each subtest. In a loop, with self.subTest(text=text): labels the case so the failure report identifies the input. With failfast off, a failed assertion in one subtest does not prevent later iterations from running.

Use assertRaises to check exceptions. With with self.assertRaises(ValueError):, run the operation inside the block. In the callable form, self.assertRaises(ValueError, int, text), pass the function without calling it, then pass its argument separately. The expected exception or a subclass satisfies the assertion; no exception fails it, and a different exception propagates.

Examples

import io
import unittest


class IntConversionTests(unittest.TestCase):
    def setUp(self):
        self.inputs = ('0', '7', '-3', 'not a number')

    def test_direct(self):
        self.assertEqual(int(self.inputs[0]), 0)
        self.assertEqual(int(self.inputs[1]), 7)
        self.assertEqual(int(self.inputs[2]), -3)
        with self.assertRaises(ValueError):
            int(self.inputs[3])

    def test_subtests(self):
        for text, expected in zip(self.inputs[:3], (0, 7, -3)):
            with self.subTest(text=text):
                self.assertEqual(int(text), expected)
        self.assertRaises(ValueError, int, self.inputs[3])


if __name__ == '__main__':
    suite = unittest.defaultTestLoader.loadTestsFromTestCase(IntConversionTests)
    report = io.StringIO()
    result = unittest.TextTestRunner(stream=report).run(suite)
    if not result.wasSuccessful():
        raise SystemExit(report.getvalue())
    print(f'{result.testsRun} tests passed')

Result

2 tests passed

`test_direct` makes three plain equality checks and checks the exception in a `with` block. `test_subtests` covers the same inputs using labeled subtests and the callable form. The `2` counts test methods, not subtests.

Related lessons

  • Python · Lesson 37 · Advanced · Version: 5
  • Python · Lesson 34 · Intermediate · Version: 3

Sources