Testing in Django REST Framework ensures reliability of business logic, API endpoints, and form validation. By testing models, views, and forms, you can confidently detect issues early and maintain stable APIs.
# Testing Book model creation and string representation
from django.test import TestCase
from .models import Book
class BookModelTest(TestCase):
def test_create_book(self):
book = Book.objects.create(title="Test Book", author="Test Author", price="19.99")
self.assertEqual(book.title, "Test Book")
self.assertEqual(book.author, "Test Author")
self.assertEqual(str(book), "Test Book")
# Testing GET request for book list API
from rest_framework.test import APITestCase
from rest_framework import status
from .models import Book
class BookViewSetTest(APITestCase):
def setUp(self):
Book.objects.create(title="Test Book", author="Test Author", price="19.99")
def test_book_list(self):
response = self.client.get('/api/books/')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 1)
self.assertEqual(response.data[0]['title'], 'Test Book')
# Testing form validation for BookForm
from django import forms
from django.test import TestCase
from .models import Book
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ['title', 'author', 'price']
class BookFormTest(TestCase):
def test_form_valid(self):
form = BookForm(data={'title':'Test Book','author':'Test Author','price':'19.99'})
self.assertTrue(form.is_valid())
def test_form_invalid(self):
form = BookForm(data={'title':'','author':'Test Author','price':'19.99'})
self.assertFalse(form.is_valid())
Simulate running a Unit Test for creating a Book. Validates that Title is present and Price is positive.