zamza
zamza

Reputation: 337

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 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

Answers (2)

abalogh
abalogh

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.

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

Upvotes: 3

Fil
Fil

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

Related Questions