Introduction
Testing models helps make sure your data and logic work correctly. It catches mistakes early so your app stays reliable.
Jump into concepts and practice - no test required
Testing models helps make sure your data and logic work correctly. It catches mistakes early so your app stays reliable.
from django.test import TestCase from .models import YourModel class YourModelTest(TestCase): def test_something(self): instance = YourModel(field='value') instance.save() self.assertEqual(instance.field, 'value')
Use TestCase from django.test to create test classes.
Test methods must start with test_ to run automatically.
from django.test import TestCase from .models import Book class BookModelTest(TestCase): def test_string_representation(self): book = Book(title='Django Basics') self.assertEqual(str(book), 'Django Basics')
from django.test import TestCase from .models import Product class ProductModelTest(TestCase): def test_price_positive(self): product = Product(price=-10) with self.assertRaises(Exception): product.full_clean()
This example defines an Item model with a method to check stock. The tests check if the method works and if negative quantity is invalid.
from django.db import models from django.test import TestCase class Item(models.Model): name = models.CharField(max_length=100) quantity = models.PositiveIntegerField() def is_in_stock(self): return self.quantity > 0 class ItemModelTest(TestCase): def test_is_in_stock(self): item = Item(name='Pen', quantity=10) self.assertTrue(item.is_in_stock()) def test_quantity_cannot_be_negative(self): item = Item(name='Notebook', quantity=-5) with self.assertRaises(Exception): item.full_clean()
Use full_clean() to run model validations in tests.
Test database is separate and resets after tests run.
Run tests with python manage.py test.
Testing models ensures your data logic is correct.
Use Django's TestCase and write methods starting with test_.
Check both data saving and custom model methods.
TestCase class?test_.def test_model(self): starts with test_, so it will be executed as a test.class Product(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class ProductTest(TestCase):
def test_str_method(self):
p = Product(name='Book')
self.assertEqual(str(p), 'Book')class UserProfile(models.Model):
age = models.IntegerField()
class UserProfileTest(TestCase):
def test_age_positive(self):
profile = UserProfile(age=-5)
self.assertTrue(profile.age > 0)class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
def full_name(self):
return f"{self.first_name} {self.last_name}"
# Test code?