📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Django Framework Django Testing

Django Testing

6 min read Quiz at the end
Write tests with TestCase, Client, assertRedirects, assertContains, and assertNumQueries.

Testing Django Apps

from django.test import TestCase, Client
from django.urls import reverse
from django.contrib.auth import get_user_model

User = get_user_model()

class PostViewTests(TestCase):
    def setUp(self):
        self.user   = User.objects.create_user("alice", "alice@test.com", "password")
        self.client = Client()
        self.post   = Post.objects.create(
            title="Test", slug="test", body="Body", author=self.user, is_draft=False
        )

    def test_post_list_returns_200(self):
        response = self.client.get(reverse("blog:post-list"))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Test")

    def test_create_post_requires_login(self):
        response = self.client.get(reverse("blog:post-create"))
        self.assertRedirects(response, "/accounts/login/?next=/posts/create/")

    def test_authenticated_user_can_create_post(self):
        self.client.login(username="alice", password="password")
        response = self.client.post(reverse("blog:post-create"), {
            "title": "New Post", "body": "Content", "is_draft": False
        })
        self.assertEqual(response.status_code, 302)
        self.assertTrue(Post.objects.filter(title="New Post").exists())
Topic Quiz · 2 questions

Test your understanding before moving on

1. Which test class does Django use?
💡 django.test.TestCase wraps each test in a transaction and resets DB state.
2. Which method simulates a logged-in user in tests?
💡 client.login() authenticates the test client with credentials.