The Test Lifecycle - setUp() and tearDown()
flowchart TD A["setUpClass -- once"] --> B["setUp"] B --> C["test_a"] C --> D["tearDown"] D --> E["setUp"] E --> F["test_b"] F --> G["tearDown"] G --> H["tearDownClass -- once"] D -.->|"runs even if the test failed"| E I["per-test state goes in setUp"] -.-> B J["expensive shared state goes in setUpClass"] -.-> A
When setUp/tearDown help
Section titled “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
Section titled “Example”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
Section titled “Rule of thumb”If your setUp becomes complex, consider:
- refactoring code
- using helper factories
- switching to pytest fixtures (Phase 4)
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Write a unittest TestCase
Section titled “Exercise 1 – Write a unittest TestCase”Exercise 2 – assertRaises
Section titled “Exercise 2 – assertRaises”Exercise 3 – setUp and tearDown
Section titled “Exercise 3 – setUp and tearDown”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading