1

I'm trying to speed up running my integration test suite. For every integration test class I have, it recreates the whole in-memory H2 database from scratch before running the tests - which takes up the most time. All methods I'm testing are within a Spring/Hibernate stack.

Is there a way to avoid recreating the db for each test while ensuring the db is in a clean state?

Some methods I'm testing call methods that start new Hibernate transactions - so not sure if it's possible to begin a new transaction before each test and roll everything back after.

Gary Russell
  • 166,535
  • 14
  • 146
  • 179
Glide
  • 20,235
  • 26
  • 86
  • 135
  • Seems like from this post http://stackoverflow.com/questions/5178708/how-to-rollback-nested-transactions-with-propagation-requires-new-in-integration there's no easy way to do so and the best solution is to recreate the db after each test. – Glide Feb 12 '14 at 00:39

1 Answers1

1

That is the default behavior (rollback) when using @Transactional with @RunWith(SpringJunit4TestRunner.class).

See the Integration Testing Chapter for complete information.

Gary Russell
  • 166,535
  • 14
  • 146
  • 179
  • Does the test rollback db even when it's testing methods that have @Transactional(propagation = Propagation.REQUIRES_NEW)? – Glide Jan 29 '14 at 20:10
  • Also if I place `Transaction` in the class level for each test, will that cause all test methods to rollback? – Glide Jan 29 '14 at 20:19
  • No; `REQUIRES_NEW` starts a new transaction which will be committed before returning to the test case. You would need to add a compensating update in the test case to undo it. Yes, class level `@Transactional` makes all test methods transactional. – Gary Russell Jan 29 '14 at 20:44
  • Is there a builtin solution with Spring to handle `REQUIRES_NEW`? It could require a lot of work to handle every method the test hits that has 'REQUIRES_NEW`. – Glide Jan 29 '14 at 21:26
  • You could write a custom transaction manager that does a rollback instead of commit; it probably wouldn't be too hard; just subclass the `HibernateTransactionManager` and override commit and call `rollback`. – Gary Russell Jan 29 '14 at 23:31