开发者

Transactional tests with Spring @ContextConfiguration - clearing database issues

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 e开发者_高级运维asy 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.


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.

http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/test/annotation/Rollback.html


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜