
问题:如何使用junit5,对同一测试样例不同方法进行测试?
需求:
- 测试用例不重复输入
- 单次的所有测试方法共用同一测试用例
解决方案:
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class Sort_Test3 {
private int[] runTest_Data;
// 每一次测试之前,都生成一份新的随机测试数据
@BeforeEach
void init_() {
this.runTest_Data = init_All();
System.out.println("run...");
}
// 具体测试方法
@Test
public void test_mpSort() {
int[] mp = MySortAlgorithm_Main.mp_sort(runTest_Data);
System.out.println("冒泡排序结果:");
}
@Test
public void test_choseSort() {
int[] cos = MySortAlgorithm_Main.chose_sort(runTest_Data);
System.out.println("选择排序结果:");
}
@Test
public void test_insertSort() {
int[] ins = MySortAlgorithm_Main.insert_sort(runTest_Data);
System.out.println("插入排序结果:");
}
// 其他测试方法
private int[] init_All() {
// 随机生成测试数据
int n = (int) (Math.random() * 1000);
System.out.println(n);
int[] testData = new int[n];
for (int i = 0; i < n; i++) {
testData[i] = (int) (Math.random() * 1000);
}
return testData;
}
}说明:
- 使用 @beforeeach 注解来在每一个测试方法之前进行初始化。
- 在 @beforeeach 方法中,生成新的测试数据并将其赋值给 runtest_data。
- 在测试方法中,直接使用 runtest_data 作为测试数据即可。
- 这样,每个测试方法都会使用同一份随机生成的测试数据。










