0
0
Djangoframework~5 mins

TestCase and SimpleTestCase in Django

Choose your learning style9 modes available
Introduction

TestCase and SimpleTestCase help you check if your Django app works correctly by running small tests automatically.

When you want to test your Django models and database interactions.
When you need to test views or templates that require database access.
When you want to test simple functions or views that do not use the database.
When you want to quickly check if your code changes break anything.
When you want to automate testing to save time and avoid manual errors.
Syntax
Django
from django.test import TestCase, SimpleTestCase

class MyTest(TestCase):
    def test_something(self):
        self.assertEqual(1 + 1, 2)

class MySimpleTest(SimpleTestCase):
    def test_simple(self):
        self.assertTrue(True)

TestCase is used when your test needs database access.

SimpleTestCase is faster and used when no database is needed.

Examples
This test checks if adding 2 and 3 equals 5 using TestCase.
Django
from django.test import TestCase

class MathTest(TestCase):
    def test_addition(self):
        self.assertEqual(2 + 3, 5)
This test checks a simple true condition without database using SimpleTestCase.
Django
from django.test import SimpleTestCase

class BasicTest(SimpleTestCase):
    def test_truth(self):
        self.assertTrue(3 > 1)
This test creates a database object and checks its name using TestCase.
Django
from django.test import TestCase
from myapp.models import Item

class ItemTest(TestCase):
    def test_create_item(self):
        item = Item.objects.create(name='Book')
        self.assertEqual(item.name, 'Book')
Sample Program

This example shows two tests: one simple math test without database and one test creating a user in the database.

Django
from django.test import TestCase, SimpleTestCase

class SimpleMathTest(SimpleTestCase):
    def test_multiply(self):
        self.assertEqual(3 * 4, 12)

class ModelTest(TestCase):
    def test_database(self):
        from django.contrib.auth.models import User
        user = User.objects.create_user(username='testuser')
        self.assertEqual(user.username, 'testuser')
OutputSuccess
Important Notes

Use TestCase when your test needs to read or write to the database.

Use SimpleTestCase for faster tests that do not touch the database.

Tests help catch bugs early and keep your app working well as you add features.

Summary

TestCase is for tests that use the database.

SimpleTestCase is for tests without database needs.

Both help you write automated tests to check your Django app works correctly.