Introduction to Django Testing
Django includes a built-in test framework based on Python's unittest. Tests verify your code works correctly, prevent regressions, and give you confidence to refactor. Django provides TestCase with a test database, client, and assertions.
15 min•By Priygop Team•Updated 2026
Testing Basics
- Django uses Python's unittest framework
- TestCase — Base class with database support
- Each test runs in a transaction that's rolled back
- Test database is created and destroyed automatically
- python manage.py test — Run all tests
- python manage.py test app_name — Run specific app tests
- Tests live in app/tests.py or app/tests/ directory
- setUp() — Run before each test method
First Test
First Test
# blog/tests.py
# from django.test import TestCase
# from django.contrib.auth.models import User
# from .models import Post
# class PostModelTest(TestCase):
# def setUp(self):
# """Runs before each test method"""
# self.user = User.objects.create_user(
# username='testuser', password='testpass123'
# )
# self.post = Post.objects.create(
# title='Test Post',
# content='Test content',
# author=self.user,
# )
#
# def test_post_creation(self):
# """Test that a post is created correctly"""
# self.assertEqual(self.post.title, 'Test Post')
# self.assertEqual(self.post.author.username, 'testuser')
#
# def test_post_str(self):
# """Test __str__ returns title"""
# self.assertEqual(str(self.post), 'Test Post')
#
# def test_post_slug_auto_generated(self):
# """Test slug is auto-generated on save"""
# self.assertEqual(self.post.slug, 'test-post')
#
# def test_post_default_not_published(self):
# """Test posts are not published by default"""
# self.assertFalse(self.post.published)
# Run: python manage.py test blog
# Output: Ran 4 tests in 0.05s OKTip
Tip
Each Django test runs in a transaction that rolls back. The database is clean for every test — no test pollution.
Diagram
Loading diagram…
QuerySets are LAZY — no DB hit until evaluated.
Common Mistake
Warning
Not writing tests. Django makes testing easy with TestCase. Untested code breaks silently in production.
Practice Task
Note
(1) Write a TestCase for a model. (2) Test __str__, save, custom methods. (3) Run with python manage.py test.
Quick Quiz
Key Takeaways
- Django includes a built-in test framework based on Python's unittest.
- Django uses Python's unittest framework
- TestCase — Base class with database support
- Each test runs in a transaction that's rolled back