详解springboot中junit回滚
时间:2020-10-07 14:25:46|栏目:JAVA代码|点击: 次
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上
上一篇:Java class文件格式之属性详解_动力节点java学院整理
栏 目:JAVA代码
下一篇:SpringBoot配置嵌入式Servlet容器和使用外置Servlet容器的教程图解
本文标题:详解springboot中junit回滚
本文地址:http://www.codeinn.net/misctech/7870.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




