服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 详解springboot中junit回滚

详解springboot中junit回滚

2021-01-28 12:02梦想修补师 Java教程

本篇文章主要介绍了springboot中junit回滚,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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

pom引入依赖

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

?
1
2
3
4
5
<dependency>
  <groupid>org.springframework.boot</groupid>
  <artifactid>spring-boot-starter-test</artifactid>
  <scope>test</scope>
</dependency>

数据库原始数据

详解springboot中junit回滚

原始数据

编写单元测试

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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上

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.jianshu.com/p/d9d0abf317c0?utm_source=tuicool&utm_medium=referral

延伸 · 阅读

精彩推荐