Monday, July 5, 2010

Database isolation in tests

Each test should be executed in database isolation. Each test should start with empty database and optionally create some fixture for its private purpose.

However the problem is how to remove data created by the test:

  • removing existing data manually is too annoying
  • listing tables automagically using JDBC and dropping their content will fail due to the foreign keys constraints
  • you cannot create new database for each test (1. too slow 2. JDBC doesn't support database management 3. Spring context should be cached between the tests)
Test data isolation is the problem indeed. My solution?
  • test classes extend AbstractTransactionalJUnit4SpringContextTests i.e. database changes are rollbacked after each test 
  • tests that cannot extend the class above (or need to be executed outside the transaction scope) have to clean after themselves manually
Follow the two rules above and you're gonna be sane.

Oh! And yes, transactional tests are bit slower but rollbacks are faster then deleting test data manually.

No comments:

Post a Comment