Skip to content

Writing Django Tests

Creating a Unit Test

  1. Create a file called test_<something>.py. The file name must begin with test_.
  2. Inside test_<something>.py, create a class which inherits from django.test.TestCase
    from django.test import TestCase
    
    
    class TestSomething(TestCase):
        pass
    
  3. (Optional) If you have data that can be reused in multiple tests, you can write a setUp method that will be ran before each test in the class. Make sure to prepend self. to your variable.
    from django.test import TestCase
    
    
    class TestSomething(TestCase):
        def setUp(self):
            self.var1 = 1
            self.var2 = 2
            ...
            # Add more reusable variables
    
  4. Write a method to test a functionality of your code. The name must start with test_.
    from django.test import TestCase
    from .my_module import add
    
    
    class TestSomething(TestCase):
        def setUp(self):
            self.var1 = 1
            self.var2 = 2
            ...
            # Add more reusable variables
    
        def test_add(self):
            expected_answer = 3
            self.assertEqual(
                add(self.var1, self.var2),
                expected_answer
            )
    

Useful information

django.test.TestCase is a subclass of unittest.TestCase from the Python standard library. As such, it has all the assert* functions available in unittest.TestCase. See here

For more general information on unittest, see here.

For information about testing specific to Django, see here.

For information about testing specific to Django REST Framework, see here.