HSQLDB / Spring unit tests not rolling back

2019-07-07 03:49发布

问题:

I am using Spring's embedded-database (default DB is HSQLDB) for running some unit tests. I have the following in my context:

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManger">
    <property name="dataSource" ref="dataSource"/>
</bean>

<jdbc:embedded-database id="dataSource">
   <jdbc:script location="blah"/>
</jdbc:embedded-database>

The unit test is as such:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=true)
@Transactional
public class DAOTest(){

   @Autowired
   public MyDAO myDAO;


   @Test
   public void test1(){
      List list = myDAO.getHibernateTemplate.loadAll(Hit.class);
      assertThat(list.size(), equalTo(0));

      Hit hit = new Hit();
      myDAO.saveHit(hit);

      list = myDAO.getHibernateTemplate.loadAll(Hit.class);
      assertThat(list.size(), equalTo(1));
   }

   @Test
   public void test2(){

      List list = myDAO.getHibernateTemplate.loadAll(Hit.class);
      assertThat(list.size(), equalTo(0));
   }

}

When I run the above, test 2 fails because a list with 1 element is returned. Why is the rollback not happening between the tests?

回答1:

So figured it out. The problem was that I was using a DataSourceTransactionManager but was using Hibernate in the code and therefore needed to use a HibernateTransactionManager.