Pattern – Test fixtures and factories
Problem: Testing a component requires the creation of various prerequisite objects before the test. Creating them explicitly in each test method gets repetitive.
Solution: Utilize factories or fixtures to create the test data objects.
Problem details
Before running each test, Django resets the database to its initial state, as it would be after running migrations. Most tests will need the creation of some initial objects to set the state. Rather than creating different initial objects for different scenarios, a common set of initial objects are usually created.
This can quickly get unmanageable in a large test suite. The sheer variety of such initial objects can be hard to read and later understand. This leads to hard-to-find bugs in the test data itself.
Being such a common problem, there are several means to reduce the clutter and write clearer test cases.
Solution details
The first solution we will take a look at is what is given in the Django documentation...