How to Use setUp and tearDown in Python unittest TestCase
Demonstrates how to structure unit tests with setUp and tearDown methods in Python's unittest framework for reusable test fixtures.
Python code
19 linesimport unittest
class ExampleTest(unittest.TestCase):
def setUp(self):
self.data = [1, 2, 3]
def tearDown(self):
self.data = None
def test_length(self):
self.assertEqual(len(self.data), 3)
def test_contains(self):
self.assertIn(2, self.data)
if __name__ == "__main__":
unittest.main(verbosity=2)
Output
test_contains (__main__.ExampleTest) ... ok
test_length (__main__.ExampleTest) ... ok
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
How it works
The setUp method runs before each test method, allowing you to prepare fresh state (like creating objects or data) so every test starts with a known baseline. The tearDown method runs after each test to clean up resources, though it's not strictly necessary if the fixture is garbage-collected automatically. This pattern is central to unittest's design—each test gets an isolated environment. Using self.data as an instance attribute makes it accessible to all test methods.
Common mistakes
- Forgetting to call `super().setUp()` when inheriting from a custom TestCase that already defines it
- Assuming setUp/tearDown run once per class instead of per test method
- Sharing mutable data across tests without resetting it in setUp
Variations
- Use `setUpClass` and `tearDownClass` for class-level setup/teardown that runs once
- Use `unittest.mock.patch` inside setUp to mock dependencies for the test
Real-world use cases
- Initializing a temporary database connection and cleaning it up after each test.
- Creating test data files in a temp directory and removing them in tearDown.
- Preparing mock API responses before each test that calls an external service.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.