Reputation: 337
I run my DAO tests within JUnit test class that has proper @ContextConfiguration and @RunWith annotations attached. Individual tests put some data to database and check sanity. They are expected to clean up database state after that. There is an easy way - mark methods/class as @Transactional, then methods are executed within a transaction and rollback happens as it should.
The problem is that this approach to DAO testing does not fully simulate the environment. Say, I have some lazy-loaded collection field in my JPA entity. In my controller code I get this entity with myDao.getMyEntity(id) call and iterate over lazy collection. What I get in application runtime is a LazyInitializationException, but this won't happen in my test as it is actually transactional. How do I run my tests with tests not being @Transactional, but data still being cleared up on test end?
I use in-memory HSQLDB for tests if it makes any difference.
Upvotes: 2
Views: 2145
Reputation: 8281
You shouldn't use @Transactional on your test methods, I assume your service layer methods and/or DAO methods have that. Use @Rollback on your test methods so that your database will be cleared after running tests.
Upvotes: 3
Reputation: 2016
I would read this to start, http://static.springsource.org/spring/docs/3.0.x/reference/testing.html#testcontext-tx
In cases where I'm testing actual data access, I usually use DBUnit to load data prior to the test, and to clean it up afterwards. In these tests, I don't use the @Transactional annotation because I want to see how my classes under test actually interact with the database, and not how they work inside of a testing environment.
Upvotes: 1