Django Django

What does Django's `TestCase` give you that `unittest.TestCase` does not?

Dima Nov 15, 2026

Short Answer

A database that resets itself between tests, without the cost of rebuilding it. Django's TestCase wraps every test method in a transaction and rolls it back afterwards, so each test starts from the same state no matter what the previous one wrote, and no DELETE statements are needed to clean up. It runs against a separate test database created and destroyed by the runner, never your development data. On top of that it adds a class-level fixture hook, setUpTestData, that builds shared rows once per class instead of once per test, plus a test client and database-aware assertions.


How It Works

The runner's first job is the database. It creates one whose name is derived from your configured database, applies migrations to it, points the connection at it, and destroys it at the end. Nothing a test does can reach the real data, which is why tests can create and delete freely.

Isolation between individual tests comes from transactions rather than truncation. Before each test method, TestCase opens an atomic block; after the method finishes — pass or fail — it rolls that block back. Every row the test inserted disappears, and the next test sees the state that existed before. Rolling back is dramatically cheaper than deleting rows and re-inserting fixtures, which is the entire reason this class exists rather than everyone using plain unittest.TestCase.

setUpTestData extends the same idea one level up. Django opens a second, outer atomic block around the whole class, runs setUpTestData once inside it, and lets every test in that class run in its own inner block nested within. Shared rows are therefore created a single time and are visible to every test, while each test's own writes still vanish. setUp, by contrast, runs before every test method as it does in plain unittest — so anything expensive belongs in setUpTestData.

There is a subtlety in that sharing. Attributes assigned in setUpTestData are class attributes, so without protection one test mutating cls.shipment.reference in memory would corrupt it for the next. Django wraps them so each test method receives its own copy of the in-memory object, and changes made to it do not carry over. The database row is shared; the Python object handed to each test is not.

Test discovery is plain unittest: the runner collects classes deriving from TestCase and, within them, methods whose names begin with test. Everything else in the class — helpers, constants — is ignored by the collector and available to the tests.


Seeing It Run

These steps share a fixture. Create settings.py, depot/models.py, and run_tests.py as shown in the first step, plus an empty depot/__init__.py, then replace depot/tests.py for each later step. Run with:

python3 run_tests.py

A real project runs python3 manage.py test; this fixture calls the same runner from a short script and captures its report so the output here is byte-stable rather than carrying a timing line.

A test class, and what the runner collects

Two test methods and one helper that is not a test.

# settings.py
SECRET_KEY = "not-a-secret"
INSTALLED_APPS = ["depot"]
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": "depot.sqlite3"}}
DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
USE_TZ = False


# depot/models.py
from django.db import models


class Shipment(models.Model):
    reference = models.CharField(max_length=20)


# run_tests.py
import contextlib
import io
import os

import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
django.setup()

from django.conf import settings
from django.test.utils import get_runner

report = io.StringIO()
with contextlib.redirect_stderr(report):
    runner = get_runner(settings)(verbosity=0, interactive=False)
    failures = runner.run_tests(["depot"])

print("failures:", failures)


# depot/tests.py
from django.test import TestCase

from depot.models import Shipment


class ManifestTests(TestCase):
    def helper_not_collected(self):
        print("  helper_not_collected ran")

    def test_database_starts_empty(self):
        print("  test_database_starts_empty:", Shipment.objects.count(), "rows")
        self.assertEqual(Shipment.objects.count(), 0)

    def test_create_then_assert(self):
        Shipment.objects.create(reference="SHP-4471")
        self.assertEqual(Shipment.objects.count(), 1)
        self.assertQuerySetEqual(
            Shipment.objects.all(),
            ["SHP-4471"],
            transform=lambda shipment: shipment.reference,
        )
        print("  test_create_then_assert: both assertions passed")


System check identified no issues (0 silenced).
  test_create_then_assert: both assertions passed
  test_database_starts_empty: 0 rows
failures: 0


helper_not_collected never runs — the collector takes only methods whose names start with test, so anything else in the class is a helper you call yourself. The two that did run executed in alphabetical order, not source order, which is why tests must never depend on each other's sequence. test_database_starts_empty finding zero rows is the first sign of the test database: the model exists, the table exists, and nothing is in it.

Try it: Rename helper_not_collected to test_helper_now_collected (and the text in its print) and run it again. The method body has not changed; what extra output appears? A third line, test_helper_now_collected ran, after the other two. The runner reads no list and no decorator: it collects the methods whose names start with test and runs them in alphabetical order.


Every test starts from the same state

Replace depot/tests.py. Two tests, each writing a row, each looking at the whole table.

# depot/tests.py
from django.test import TestCase

from depot.models import Shipment


class IsolationTests(TestCase):
    def test_one_creates_a_row(self):
        Shipment.objects.create(reference="SHP-4471")
        print("  test_one sees", Shipment.objects.count(), "row(s)")

    def test_two_creates_a_row(self):
        Shipment.objects.create(reference="SHP-4408")
        print("  test_two sees", Shipment.objects.count(), "row(s)")
        print("  test_two finds SHP-4471:", Shipment.objects.filter(reference="SHP-4471").exists())


System check identified no issues (0 silenced).
  test_one sees 1 row(s)
  test_two sees 1 row(s)
  test_two finds SHP-4471: False
failures: 0


Two rows were created and neither test ever sees two. test_two runs after test_one and finds a single row — its own — because the transaction wrapping test_one was rolled back the moment that method returned. The last line makes it explicit: SHP-4471 is gone. No cleanup code was written anywhere, and none is needed; the rollback is the cleanup, which is why this is fast enough to do for every test in a suite.


setUpTestData runs once, setUp runs every time

Replace depot/tests.py. Counters on the class record how often each hook fires, and one test mutates the shared object to see whether it leaks.

# depot/tests.py
from django.test import TestCase

from depot.models import Shipment


class FixtureCostTests(TestCase):
    calls = {"setUpTestData": 0, "setUp": 0}

    @classmethod
    def setUpTestData(cls):
        FixtureCostTests.calls["setUpTestData"] += 1
        cls.shipment = Shipment.objects.create(reference="SHP-4471")

    def setUp(self):
        FixtureCostTests.calls["setUp"] += 1

    def test_a_mutates_the_shared_object(self):
        self.shipment.reference = "MUTATED"
        print("  test_a set it to", self.shipment.reference)

    def test_b_sees_the_original(self):
        print("  test_b sees", self.shipment.reference)
        print("  rows in the database:", Shipment.objects.count())

    def test_c_reports_how_often_each_ran(self):
        print("  setUpTestData ran", FixtureCostTests.calls["setUpTestData"], "time(s)")
        print("  setUp ran", FixtureCostTests.calls["setUp"], "time(s) so far")


System check identified no issues (0 silenced).
  test_a set it to MUTATED
  test_b sees SHP-4471
  rows in the database: 1
  setUpTestData ran 1 time(s)
  setUp ran 3 time(s) so far
failures: 0


One setUpTestData call served three tests, while setUp ran three times — the cost difference that makes the class-level hook worth using for anything that touches the database. test_a renamed the shared object to MUTATED and test_b, running next, still sees SHP-4471: each test gets its own copy of the in-memory instance, so the mutation could not escape. The row count stays at one throughout, because the shared row lives in the outer transaction that only rolls back when the class finishes.

Try it: Make test_a properly destructive: replace its body with Shipment.objects.all().delete() and print(" test_a deleted everything:", Shipment.objects.count(), "rows"). The row was created once, in setUpTestData; how many rows will test_b see? test_a reports 0 rows, and test_b still sees SHP-4471 and rows in the database: 1. The deletion was real inside the test and rolled back at its end, because every test runs in a transaction of its own, on top of the class's data.


Edge Cases and Gotchas

  • TransactionTestCase when you need real commits. Code under test that calls transaction.on_commit, or that must be visible to another connection, needs a class that truncates tables instead of rolling back — slower, and it resets sequences differently.
  • SimpleTestCase forbids database access. For tests of pure functions, template rendering, or URL resolution, it fails loudly if a query is attempted, which keeps fast tests honestly fast.
  • Tests run in alphabetical order within a class. The runner also groups by class and app, so any test that depends on another having run first will eventually break.
  • assertNumQueries guards against N+1 regressions. Wrapping a view call in with self.assertNumQueries(3): turns a query-count expectation into a failing test when someone removes a select_related.
  • The test database is created from migrations, not from your dev data. A model change without a migration passes locally and fails in the test run, which is usually how the missing migration is discovered.

Summary

Django's TestCase adds a disposable test database and per-test transaction rollback to plain unittest, making isolation cheap enough to apply everywhere. setUpTestData shares expensive fixture rows across a class while still handing each test its own in-memory copy.

  • The runner creates a separate test database, migrates it, and destroys it afterwards; the real database is never touched.
  • Each test method runs inside a transaction that is rolled back when it finishes, so tests never need cleanup code and never see each other's rows.
  • setUpTestData runs once per class inside an outer transaction; setUp runs before every test method, so put database fixtures in the former.
  • Objects assigned in setUpTestData are copied per test, so mutating one in memory does not affect the next test, while the underlying row stays shared.
  • Only methods whose names begin with test are collected, and they run in alphabetical order — never write tests that depend on ordering.

You need to be logged in to access the cloud lab.

Log in