JUnit 有序测试执行示例

JUnit 有序测试执行示例

原文: https://howtodoinjava.com/junit/ordered-testcases-execution-in-junit-4/

编写 JUnit 有序测试案例被认为是不良做法。 但是,如果仍然遇到测试用例排序是唯一出路的情况,则可以使用MethodSorters类。

1. JUnit 方法排序器

从 JUnit4.11 版本开始引入MethodSorters。 此类声明了三种执行顺序,可以在测试用例中使用它们。

  1. MethodSorters.DEFAULT – 以确定但不可预测的顺序对测试方法进行排序。
  2. MethodSorters.JVM - 按照 JVM 返回的顺序保留测试方法。
  3. MethodSorters.NAME_ASCENDING按方法名称依字典顺序对测试方法进行排序,并使用Method.toString()作为平局。

2. JUnit 有序测试示例 – NAME_ASCENDING

让我们看看如何在 JUnit 中编写和执行有序的测试。

import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

//Running test cases in order of method names in ascending order
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class OrderedTestCasesExecution 
{
	@Test
	public void secondTest() {
		System.out.println("Executing second test");
	}

	@Test
	public void firstTest() {
		System.out.println("Executing first test");
	}

	@Test
	public void thirdTest() {
		System.out.println("Executing third test");
	}
}

程序输出。

Executing first test
Executing second test
Executing third test

2. JUnit 有序测试示例 – JVM

现在使用JVM选项执行相同的测试。

package corejava.test.junit;

import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

//Running test cases in order of method names in ascending order
@FixMethodOrder(MethodSorters.JVM)
public class OrderedTestCasesExecution {
	@Test
	public void secondTest() {
		System.out.println("Executing second test");
	}

	@Test
	public void firstTest() {
		System.out.println("Executing first test");
	}

	@Test
	public void thirdTest() {
		System.out.println("Executing third test");
	}
}

程序输出:

Executing third test
Executing first test
Executing second test

显然,只有NAME_ASCENDING顺序可让您控制真正的顺序,而其他两个选项在测试执行顺序序列中对于开发人员而言却无法提供足够的可预测性。

在此 JUnit 教程中,我们学习了编写 JUnit 顺序测试的过程。 让我知道你的想法。

学习愉快!

参考:

MethodSorters