Skip to content

The Test Lifecycle - setUp() and tearDown()

diagram the order setUp, setUpClass and their teardowns actually run mermaid
setUp runs before every test method and tearDown after it, so each test starts from the same state. setUpClass runs once for the whole class, which is where expensive shared work goes -- and which is why anything it creates is shared, and can be polluted by one test for the next.

Use them when each test needs:

  • a fresh object
  • temporary files
  • a test database connection (prefer fixtures/mocks for unit tests)
setup_teardown.py
import unittest
 
 
class TestListOps(unittest.TestCase):
    def setUp(self):
        self.items = [1, 2, 3]
 
    def tearDown(self):
        # cleanup if needed
        self.items = []
 
    def test_append(self):
        self.items.append(4)
        self.assertEqual(self.items, [1, 2, 3, 4])
 
    def test_pop(self):
        self.items.pop()
        self.assertEqual(self.items, [1, 2])

If your setUp becomes complex, consider:

  • refactoring code
  • using helper factories
  • switching to pytest fixtures (Phase 4)

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading