Don't clean up, prepare!
A classical way of doing database tests is to start from an empty database, populate the database before each test, run the test, then remove the data after the test.
This approach is not satisfactory:
- if the database is not empty before the test, it fails;
- if a test fails, inspecting the contents of the database after a test can be useful;
- most of the tests are read-only, and inserting and removing the same data set again and again makes the tests slow. And slow tests are bad.
We recommend using multiple very small data sets, specific for each test class. If you insert less data, the tests will be faster.
We thus recommend the following strategy:
- clear the database before the test,
- then insert a small data set,
- then run the test,
- then leave the database as it is.
If another test is run after, it will start by clearing the database, and everything will be fine. That means that each test must start by clearing all the tables, and not just the tables it uses. You want your tests to be independent, and able to run in whatever order.