Django — Testing
Basic Test
# blog/tests.py
from django.test import TestCase
from django.urls import reverse
from .models import Post
class PostTestCase(TestCase):
def setUp(self):
Post.objects.create(title='Test Post', content='Test content')
def test_post_creation(self):
post = Post.objects.get(title='Test Post')
self.assertEqual(post.content, 'Test content')
def test_post_list_view(self):
response = self.client.get(reverse('post-list'))
self.assertEqual(response.status_code, 200)
Test Client
class ViewTests(TestCase):
def test_get(self):
response = self.client.get('/blog/')
self.assertEqual(response.status_code, 200)
def test_post(self):
response = self.client.post('/blog/create/', {
'title': 'New Post',
'content': 'Content'
})
self.assertEqual(response.status_code, 302)
Assertions
| Assertion | Description |
|---|---|
| assertEqual | Values are equal |
| assertTrue | Expression is true |
| assertFalse | Expression is false |
| assertRaises | Exception is raised |
| assertContains | Response contains text |
Run Tests
python manage.py test
python manage.py test blog
python manage.py test blog.tests.PostTestCase
Mini Practice
- Write model tests
- Write view tests
- Use test client
- Run test suite
Up Next
Continue with Deployment — deploying Django applications.
Related Topics
Frequently Asked Questions about Testing
What is Testing in Django?
Testing is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Testing?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Testing.
Why is Testing important in Django?
Testing is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.