弹簧测试在测试后不回滚
Posted
技术标签:
【中文标题】弹簧测试在测试后不回滚【英文标题】:Spring test does not roll back after test 【发布时间】:2013-04-08 14:39:21 【问题描述】:我有一系列使用 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="&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】:没关系,我自己找到了解决方案。这根本不是回滚问题吗? 我的 findAllBla() 方法有错误?它需要一个:
.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
【讨论】:
以上是关于弹簧测试在测试后不回滚的主要内容,如果未能解决你的问题,请参考以下文章
在集成测试中每个方法不回滚后 Spring Data JPA 数据库更改