0
我有一系列使用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 {