Wednesday 30 November 2011

Spring+JUnit: the db results of a method are persisted during methods calls

Problem description

I want the db to become empty on each method call of a JUnit Test. My persistence.xml contains
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
The service layer is transactional (@Transactional) and my test is transactional ("defaultRollback = true"). But db changes are persisted among method calls so my tests fail!
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
public class MyTest {

 @Test
 public void test1() { 
          /*db is empty*/ 
          write sth to db;
          /*db is empty*/ 
        }

 @Test
 public void test2() {
          /*db is NOT empty*/
        }

Solution

Test should extend AbstractTransactionalJUnit4SpringContextTests

No comments:

Post a Comment