Writing Django Tests
Creating a Unit Test¶
- Create a file called
test_<something>.py
. The file name must begin withtest_
. - Inside
test_<something>.py
, create aclass
which inherits fromdjango.test.TestCase
from django.test import TestCase class TestSomething(TestCase): pass
- (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 theclass
. Make sure to prependself.
to your variable.from django.test import TestCase class TestSomething(TestCase): def setUp(self): self.var1 = 1 self.var2 = 2 ... # Add more reusable variables
- 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.