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.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 13 views 0 copies

Python code

19 lines
Python 3.9+
import 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

stdout
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

  1. Use `setUpClass` and `tearDownClass` for class-level setup/teardown that runs once
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Testing & modern typing

Related tutorials and quizzes for this topic.