Using setUp and tearDown

A snippet showing how to use setUp and tearDown in Django tests.


# models.py

from django.db import models

class Profile(models.Model):
    email = models.EmailField(unique=True)
      

# admin.py

from django.contrib import admin
from .models import Profile

@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
    list_display = ("email",)
      

# Result (tests/test_setup_teardown.py)
from django.test import TestCase
from .models import Profile

class ProfileTest(TestCase):
    def setUp(self):
        self.user = Profile.objects.create(email="[email protected]")
    def tearDown(self):
        Profile.objects.all().delete()
    def test_exists(self):
        self.assertTrue(Profile.objects.filter(email="[email protected]").exists())
      
Explanation:
  • Use setUp() for per-test fixtures and tearDown() for cleanup.
  • For expensive setup, prefer setUpTestData classmethod to create data once.
  • Category Testing
  • Total Views 569
  • Last Modified 27 February, 2026
  • Tags #testing #setup #teardown #unittest
Previous snippet
Testing Signals
Next snippet
Testing with Fixtures
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.