在 Sring 中进行单元测试,如果不想改变数据库结构,则需要事物回滚来保持数据库的数据完整。
1. 在 xml 配置文件中设置事物
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--事务-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource" name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
destroy-method="close">
<!-- 指定连接数据库的驱动-->
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<!-- 指定连接数据库的URL-->
<property name="url"
value="jdbc:mysql://127.0.0.1:3306/mydb/>
<!-- 指定连接数据库的用户名-->
<property name="username" value="xxx"/>
<!-- 指定连接数据库的密码-->
<property name="password" value="xxx"/>
<property name="useUnfairLock" value="true"/>
<!--获取连接到时候检查连接是否有效,会略降低性能 -->
<property name="testOnBorrow" value="true"/>
<property name="testOnReturn" value="false"/>
<!-- 验证连接有效与否的SQL,不同的数据配置不同 -->
<property name="testWhileIdle" value="true"/>
<property name="validationQuery" value="select 1 "/>
</bean>
</beans>
2.在单元测试类中增加事务注解
@TransactionConfiguration(transactionManager = "transactionManager")
@Transactional()
@TransactionConfiguration
默认都是回滚事务的,也就是说默认 Rollback=true
等同于:
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional()
在测试方法上使用 @Rollback(true)
或 @Rollback(false)
可对单独的方法进行回滚或不回滚控制。
示例
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:test-spring-mybatis.xml",
"classpath:test-service-application.xml",
"classpath:test-application-cache.xml",
"classpath:test-sinocare-event.xml"
})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional()
public class CustomerTagServiceTest {
@Autowired
private CustomerTagService customerTagService;
@Test
public void testList(){
List<CustomerTagVo> customerTagVoList = customerTagService.list().getData();
Assert.assertNotNull(customerTagVoList);
}
@Test
@Transactional
@Rollback(true)
public void testAdd(){
CustomerTagVo tagVo = new CustomerTagVo();
tagVo.setName("极品客户");
Boolean result = customerTagService.add(tagVo).getData();
Assert.assertTrue(result);
}
}