温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

springboot中junit回滚有什么作用

发布时间:2023-05-18 13:56:58 来源:亿速云 阅读:105 作者:iii 栏目:编程语言

这篇文章主要介绍“springboot中junit回滚有什么作用”,在日常操作中,相信很多人在springboot中junit回滚有什么作用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”springboot中junit回滚有什么作用”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

springboot中使用junit编写单元测试,并且测试结果不影响数据库。

pom引入依赖

如果是IDE生成的项目,该包已经默认引入。

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>

数据库原始数据

springboot中junit回滚有什么作用

原始数据

编写单元测试

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);
  }

}

结果数据

springboot中junit回滚有什么作用

结果数据

结论

可以看出code=001001的数据没有更改,而code=001003的数据修改成功。回头看代码:

@Transactional表示该方法整体为一个事务,

@Rollback表示事务执行完回滚,支持传入一个参数value,默认true即回滚,false不回滚。

该注解一样支持对类的注解,若如此做,对整个class的方法有效。

springboot中junit回滚有什么作用

注解在class上

到此,关于“springboot中junit回滚有什么作用”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI