CKTIS / Python
`unittest.TestCase.setUp`: prepare each test
Use `setUp()` to give each test fresh data, then check values with `assertEqual()` and an expected exception with `assertRaises()`.
Version: Python 3.12
Syntax
import unittest
class ExampleTests(unittest.TestCase):
def setUp(self):
self.items = [10, 20]unittest.TestCase.setUp is an instance method that unittest calls automatically just before each test method it runs. Define setUp(self) in a unittest.TestCase subclass and store the test data, part of the test fixture, on self. The default implementation does nothing.
unittest creates a separate TestCase instance for each test method. Create a new list in setUp() rather than sharing a mutable list as a class attribute. In the example, test_pop changes its list, while test_remove_missing starts with a fresh [10, 20]. setUpClass() is a class method for shared class-level preparation, not per-test initialization.
The three assertEqual(actual, expected) calls check value equality, not object identity: they check the returned item, the list after popping, and the list after an unsuccessful removal. with self.assertRaises(ValueError): wraps only the attempt to remove the missing value. If no exception is raised, the assertion fails; a different exception propagates. The alternative callable form is self.assertRaises(ValueError, self.items.remove, 99).
If setUp() raises, neither the test method nor tearDown() runs. AssertionError counts as a failure, unittest.SkipTest as a skip, and most other exceptions as errors. Cleanups already registered with addCleanup() still run when unittest records a failure, error, or skip during setup. In Python 3.12, however, if KeyboardInterrupt escapes setUp(), it propagates out of TestCase.run() before doCleanups() is called. If setup succeeds, tearDown() runs even if the test fails.
Examples
import unittest
class ListTests(unittest.TestCase):
def setUp(self):
self.items = [10, 20]
def test_pop(self):
removed = self.items.pop()
self.assertEqual(removed, 20)
self.assertEqual(self.items, [10])
def test_remove_missing(self):
with self.assertRaises(ValueError):
self.items.remove(99)
self.assertEqual(self.items, [10, 20])
if __name__ == "__main__":
suite = unittest.defaultTestLoader.loadTestsFromTestCase(ListTests)
result = unittest.TestResult()
suite.run(result)
print(f"Tests run: {result.testsRun}")
print(f"Successful: {result.wasSuccessful()}")
raise SystemExit(0 if result.wasSuccessful() else 1)
Result
Tests run: 2 Successful: True
Run `python list_tests.py` with Python 3.12. The expected output shows that two tests ran and the suite succeeded; the script does not print elapsed time.
Related lessons
- Python · Lesson 34 · Intermediate · Version: 3