October 21, 2020
Django comes with a handful of different base classes for unit tests, three of which we'll explore:
SimpleTestCase
— An extension of unittest.TestCase
that adds new assertion helpersTransactionTestCase
— A class that allows unit tests to set up their own top-level transactionsTestCase
— A class that wraps each unit test run inside of a transactionThe naming is confusing. One would expect TransactionTestCase
to run tests in a transaction, but it doesn't work that way.
The class hierarchy looks like this:
unittest.TestCase
django.test.SimpleTestCase
django.test.TransactionTestCase
django.test.TestCase
Most Django apps are going to use TestCase
, but some may need TransactionTestCase
. So let's focus on those.
<aside> 💡 Djblets and Review Board have their own specialized classes
If you're developing code for either of these, you'll need to build unit tests off of those classes. See Writing Unit Tests.
</aside>
TransactionTestCase
As stated above, this class is best used when you have unit tests that need to be able to manage their own transaction. The name is confusing. TransactionlessTestCase
might be a better name.