Django Test Fixture: setUp, setUpClass and setUpTestData

Nguyen Nhat Cuong
Jan 15, 2017 · 5 min read

First thing first: The TestCase class

from unittest import TestCaseclass DummyTestCase(TestCase):
def test_bigger(self):
self.assertTrue(2>1)

def test_smaller(TestCase):
self.assertTrue(1<2)
bigger_test_case = DummyTestCase('test_bigger')
smaller_test_case = DummyTestCase('test_smaller')

setUp and tearDown: the most basic fixture methods

from django.test import TestCase
from django.contrib.auth.models import User
class DummyTestCase(TestCase):
def setUp(self):
User.objects.create(username='dummy')

def test_a(self):
self.assertTrue(1<2)
is equivalent to:
from django.test import TestCase
from django.contrib.auth.models import User
class DummyTestCase(TestCase):
def test_a(self):
User.objects.create(username='dummy')
self.assertTrue(1<2)

setUpClass and tearDownClass: a bit of magic

from django.test import TestCaseclass DummyTestCase(TestCase):
@classmethod
def setUpClass(cls):
super(DummyTestCase, cls).setUpClass()
# some code

setUpTestData: a specific solution for a specific problem

Conclusion

Nguyen Nhat Cuong

Written by

Books, code and my life in between

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade