Unit testing ensures the correctness of your Django REST Framework APIs. You can test views, serializers, and models using Python’s built-in unittest or the popular pytest framework.
Django provides TestCase and DRF extends it with APITestCase. Pytest offers decorators, fixtures, and simpler assertions.
# Testing API views using DRF APITestCase
from rest_framework.test import APITestCase
from rest_framework import status
from .models import Book
class BookTests(APITestCase):
def setUp(self):
# Create initial test data
Book.objects.create(title="Test Book", author="Test Author", price="19.99")
def test_book_list(self):
# Verify GET request for book list
response = self.client.get('/api/books/')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 1)
def test_create_book(self):
# Verify POST request for creating a book
data = {'title': 'New Book','author':'New Author','price':'29.99'}
response = self.client.post('/api/books/', data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
# Pytest style testing for DRF APIs
import pytest
from rest_framework import status
from .models import Book
@pytest.mark.django_db
def test_book_list(client):
# Arrange test data
Book.objects.create(title="Test Book", author="Test Author", price="19.99")
response = client.get('/api/books/')
assert response.status_code == status.HTTP_200_OK
@pytest.mark.django_db
def test_create_book(client):
# Create a book using POST request
data = {'title':'New Book','author':'New Author','price':'29.99'}
response = client.post('/api/books/', data, format='json')
assert response.status_code == status.HTTP_201_CREATED
Successful tests return HTTP 200 or 201 responses. Any failure produces detailed error output in the terminal.
Think of each test as a simulation of a real client request validating your API endpoints automatically.
Try running the test. If you leave the Title empty, the test will FAIL (just like in DRF).