Skip to content

The Test Lifecycle - setUp() and tearDown()

When setUp/tearDown help

Use them when each test needs:

  • a fresh object
  • temporary files
  • a test database connection (prefer fixtures/mocks for unit tests)

Example

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])
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])

Rule of thumb

If your setUp becomes complex, consider:

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

๐Ÿงช Try It Yourself

Exercise 1 โ€“ Write a unittest TestCase

Exercise 2 โ€“ assertRaises

Exercise 3 โ€“ setUp and tearDown

If this helped you, consider buying me a coffee โ˜•

Buy me a coffee

Was this page helpful?

Let us know how we did