首页 技术 正文
技术 2022年11月9日
0 收藏 931 点赞 4,228 浏览 1814 个字

  我们在写JUnit测试用例时,有时候需要按照定义顺序执行我们的单元测试方法,比如如在测试数据库相关的用例时候要按照测试插入、查询、删除的顺序测试。如果不按照这个顺序测试可能会出现问题,比如删除方法在前面执行,后面的方法就都不能通过测试,因为数据已经被清空了。而JUnit测试时默认的顺序是随机的。所以这时就需要有办法要求JUnit在执行测试方法时按照我们指定的顺序来执行。JUnit是通过@FixMethodOrder注解(annotation)来控制测试方法的执行顺序的。

  JUnit是通过@FixMethodOrder注解(annotation)来控制测试方法的执行顺序的。@FixMethodOrder注解的参数是org.junit.runners.MethodSorters对象,在枚举类org.junit.runners.MethodSorters中定义了如下三种顺序类型:

  • MethodSorters.JVM(代码定义的顺序)

Leaves the test methods in the order returned by the JVM. Note that the order from the JVM may vary from run to run (按照JVM得到的方法顺序,也就是代码中定义的方法顺序)

  • MethodSorters.DEFAULT(默认的顺序(无序随机))

Sorts the test methods in a deterministic, but not predictable, order() (以确定但不可预期的顺序执行)

  • MethodSorters.NAME_ASCENDING(方法名字母顺序)

Sorts the test methods by the method name, in lexicographic order, with Method.toString() used as a tiebreaker (按方法名字母顺序执行)

举例说明

以下的代码,定义了三个方法testAddAndGet,testSearch,testRemove,我设计的时候,是希望三个方法按定义的顺序来执行。

package test;import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RunWith(SpringRunner.class)
@SpringBootTest
@FixMethodOrder(MethodSorters.JVM)//指定测试方法按定义的顺序执行
public class TestJNI { private static final Logger logger =LoggerFactory.getLogger(TestJNI.class);@Test
public void testAddAndGet(){
logger.info("test ‘addBean’ and ‘getBean’ ");
}@Test
public final void testSearch() {
logger.info("test search CODE from JNI memory...");
}@Test
public final void testRemove() {
logger.info("test remove CODE from JNI memory...");
} }

如果@FixMethodOrder定义为MethodSorters.DEFAULT或去掉代码中的@FixMethodOrder注解,那么测试用便执行的顺序是

可以看到 程序的执行是没有顺序的,先运行的testAddAndGet -> testRemove -> testSearch

这并不是我要的结果,testRemove如果先执行了,testSearch肯定什么也找不到

 

如果改成@FixMethodOrder(MethodSorters.JVM),则这个执行顺序才是我想要的顺序。

可以看到程序的执行顺序是:testAddAndGet -> testSearch -> testRemove

文章转载至:https://blog.csdn.net/hehyyoulan/article/details/84959113

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,104
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,581
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,428
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,835
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,918