Testing in Django: Writing Your First Unit Test

3D isometric illustration of a robot inspector checking a Django web page, representing unit testing.

You’ve built a Django app. It works today, but will it work tomorrow after you change some code? If you want to understand the essentials of testing your project, this Django Testing Guide will help you get started. Django has a powerful test runner built on top of Python’s <a href="https://pythonprohub.com/python-testing/python-unittest-beginner-guide/" target="_blank" rel="noreferrer noopener">unittest</a>.

Step 1: Testing a Model

Let’s test our Post model to ensure it saves data correctly. Open pages/tests.py (Django creates this file for you).

from django.test import TestCase
from .models import Post

class PostModelTest(TestCase):
    def setUp(self):
        # Create a sample post before each test
        Post.objects.create(title='Test Post', text='Just a test.')

    def test_text_content(self):
        # Get the post we just created
        post = Post.objects.get(id=1)
        expected_title = f'{post.title}'
        expected_text = f'{post.text}'
        
        # Check if it matches what we expect
        self.assertEqual(expected_title, 'Test Post')
        self.assertEqual(expected_text, 'Just a test.')

Step 2: Testing a View (Page Load)

Does your homepage actually load? Let’s test it.

# Add this to pages/tests.py
from django.urls import reverse

class HomePageViewTest(TestCase):
    def setUp(self):
        Post.objects.create(title='Another Test', text='testing...')

    def test_view_url_exists_at_proper_location(self):
        resp = self.client.get('/')
        # 200 means "OK" (page loaded successfully)
        self.assertEqual(resp.status_code, 200)

    def test_view_uses_correct_template(self):
        resp = self.client.get(reverse('home'))
        self.assertEqual(resp.status_code, 200)
        self.assertTemplateUsed(resp, 'pages/home.html')

Step 3: Run the Tests

python manage.py test

Django will create a temporary database, run your tests, and report the results.

Similar Posts

Leave a Reply