setUp is a test lifecycle method that runs immediately before each test method. Use it to create the shared starting state that every test needs, such as ORM objects, while keeping each test independent. section 8.3
Listing 8.2 A test case for the musician view
# bands/tests.py
from datetime import date
from django.test import TestCase
from bands.models import Musician
class TestBands(TestCase):
def setUp(self): #1
self.musician = Musician.objects.create(first_name="First",
last_name="Last", birth=date(1900, 1, 1))
def test_musician_view(self):
url = f"/bands/musician/{self.musician.id}/"
response = self.client.get(url) #2
self.assertEqual(200, response.status_code)
self.assertEqual(response.context['musician'].id,
self.musician.id) #3
self.assertIn(self.musician.first_name,
str(response.content)) #4
The example creates a Musician in setUp, stores it as self.musician, requests the musician view, and checks the response status, context, and rendered content. section 8.3
A typical setUp flow looks like this:
- Create the required model instance through the ORM inside setUp(). section 8.3
- Assign the instance to self so every test method can use it. section 8.3
- Exercise the view with Django’s test client and assert the expected response. section 8.3 section 8.10
- Rely on Django’s per-test transaction rollback to return the database to a clean state afterward. section 8.3

