Basic Django Unit Test
A snippet showing how to write a basic Django unit test.
# models.py
from django.db import models
class Item(models.Model):
name = models.CharField(max_length=100)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.name
def toggle(self):
self.is_active = not self.is_active
return self.is_active
# admin.py
from django.contrib import admin
from .models import Item
@admin.register(Item)
class ItemAdmin(admin.ModelAdmin):
list_display = ("name", "is_active")
# Result (tests/test_basic.py)
from django.test import TestCase
from .models import Item
class ItemTest(TestCase):
def test_toggle(self):
it = Item.objects.create(name="A")
self.assertEqual(it.is_active, True)
it.toggle()
self.assertEqual(it.is_active, False)
Explanation:
-
Use
django.test.TestCasefor isolated tests with a transaction and test database. -
Name files like
tests/test_*.pyfor discovery with pytest or Django. - Keep tests small and focused on one behavior.
- Category Testing
- Total Views 565
- Last Modified 22 February, 2026
- Tags #testing #unit test #basics #django
Previous snippet
Limit Login Attempts with Throttling
Next snippet