弹簧测试在测试后不会回滚

时间:2013-04-08 14:39:22

标签: spring unit-testing transactions h2 spring-test

我使用Spring测试和H2内存数据库进行了一系列集成测试。我注意到每次测试后都不会回滚h2数据库。

这是我的配置:

@RunWith(SpringJUnit4ClassRunner.class)
public class BlaServiceIntegrationTest extends AbstractTest {

@Autowired
private BlaService blaService;

@Test()
public void doBla() {
    // some other test that writes in the database
}

@Test()
public void saveNewBla() {
    assertEquals(0, findAllBlas().size()); // <-- fails, the db is not empty.
             // the previous test did not roll back
}

然后是AbstractTest:

@ContextConfiguration(locations = { "classpath:test-with-db.xml" })
@TransactionConfiguration(defaultRollback = true)
@Transactional()
public class AbstractTest {


private static final Logger LOG = LoggerFactory.getLogger(AbstractTest.class);

@Autowired
protected SessionFactory sessionFactory;


public AbstractTest() {
    super();
}

@SuppressWarnings("unchecked")
protected List<Bla> findAllBlas() {
    return sessionFactory.getCurrentSession().createCriteria(Bla.class).list();
}

Spring配置:

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource "
    p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
    p:username="${jdbc.username}" p:password="${jdbc.password}">
</bean>

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl}</prop>
            <!-- <prop key="hibernate.use_sql_comments">false</prop> -->

        </props>
    </property>
    <property name="packagesToScan" value="com.company.bla.back.domain"></property>
</bean>


<bean id="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager"
    p:sessionFactory-ref="sessionFactory">
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="hibernateConfiguration" factory-bean="&amp;sessionFactory"
    factory-method="getConfiguration" />

特定于测试的config.properties:

################### MySQL JDBC Configuration ##################
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem;DB_CLOSE_ON_EXIT=FALSE
jdbc.username=
jdbc.password=

################### Hibernate Configuration ##########################
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=false
hibernate.hbm2ddl=create-drop
hibernate.generate_statistics=false

正在测试的服务:

@Service("blaService")
@Transactional(propagation = Propagation.MANDATORY)
public class BlaServiceImpl implements BlaService {

1 个答案:

答案 0 :(得分:0)

没关系,我自己找到了解决方案。这根本不是回滚问题? 我的findAllBla()方法有错误吗?它需要一个:

 .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)