详解springboot中junit回滚
springboot中使用junit编写单元测试,并且测试结果不影响数据库。
pom引入依赖
如果是IDE生成的项目,该包已经默认引入。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
数据库原始数据

原始数据
编写单元测试
package com.mos.quote;
import com.mos.quote.model.Area;
import com.mos.quote.service.IAreaService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class QuoteApplicationTests {
@Autowired
private IAreaService areaService;
@Test
public void contextLoads() {
}
@Test
public void testUpdate(){
Area area = new Area();
area.setCode("001003");
area.setName("洛阳市");
Integer result = areaService.update(area);
Assert.assertEquals(1, (long)result);
}
@Test
@Transactional
@Rollback
public void testUpdate4Rollback(){
Area area = new Area();
area.setCode("001001");
area.setName("郑州市123");
Integer result = areaService.update(area);
Assert.assertEquals(1, (long)result);
}
}
结果数据

结果数据
结论
可以看出code=001001的数据没有更改,而code=001003的数据修改成功。回头看代码:
@Transactional表示该方法整体为一个事务,
@Rollback表示事务执行完回滚,支持传入一个参数value,默认true即回滚,false不回滚。
该注解一样支持对类的注解,若如此做,对整个class的方法有效。

注解在class上
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
解决springboot+activemq启动报注解错误的问题
这篇文章主要介绍了解决springboot+activemq启动报注解错误的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-07-07
MyBatis3传递多个参数(Multiple Parameters)
这篇文章主要介绍了MyBatis3传递多个参数,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-07-07
mall整合SpringSecurity及JWT认证授权实战下
这篇文章主要为大家介绍了mall整合SpringSecurity及JWT认证授权实战第二篇,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-06-06
使用springboot单元测试对weblistener的加载测试
这篇文章主要介绍了使用springboot单元测试对weblistener的加载测试,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-10-10


最新评论