我有一系列使用 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();
}
弹簧配置:
<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 {