setUpClass() prepares shared test-class configuration once, before the class's test methods run. It can populate ORM models or establish other initial state more efficiently than repeating setup for every test. section 8.3 section 8.10
When adding setUpClass() to a Django TestCase:
- Decorate it with @classmethod; otherwise Python will not treat it as a class method. section 8.3
- Call super().setUpClass() so Django's parent setup still runs; skipping it causes an error. section 8.3
- Use setUp() instead when each test needs a fresh setup, because setUp() runs before every test method. section 8.3
A class-level setup pattern
class TestBands(TestCase): @classmethod def setUpClass(cls): super().setUpClass() # Create shared test configuration or initial data here def test_musician_view(self): response = self.client.get('/bands/musician/1/') self.assertEqual(200, response.status_code) section 8.3 section 8.10
Figure 8.4 Order of method invocation of a TestCase class
Use the lifecycle diagram to place setUpClass() alongside per-test setup, test methods, and teardown callbacks. section 8.3
