Suppose I have component A
,B
,C
that all put some data into a database. Each component depends on data in the database inserted by the previous component.
How do I test these modules in isolation? I already have tests at the unit level, but I now want to test with the database. I have seen suggestions to make a dump of the database for each step, but this is a messy thing to check in to version control and requires a lot of effort whenever the architecture changes (which where I work translates to “abandon tests!”).
I really think that the best approach is to clear my test database before running tests and use some tool to specify test dependencies to ensure correct running order, but this seems to be seriously frowned upon by the opinions I’ve read. To me it seems the same as using a fixture for each step, except that the fixture is just a cheap way of hiding the dependency.
3
So on a high level you create data sets in code that are applied for each test case.
After each test the database is rolled back either by dropping and recreating or truncating.
You don’t mention the framework or language you are using, but many have methods for using fixtures to create data for your tests that are reset during each test cycle.
What you need to do is pick one of these frameworks and setup the core set of data elements you need for your application. Then for each test, the test framework should have a mechanism to populate specific objects (rows) with the data you need for that test scenario. The framework should then reload the database and and apply the default data for the next test.
https://github.com/notahat/machinist is and example of a fixture framework for Ruby on Rails.