如何使用 JUnit5 对同一测试用例的不同排序算法进行测试?
IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天米云给大家整理了《如何使用 JUnit5 对同一测试用例的不同排序算法进行测试?》,聊聊,我们一起来看看吧!

问题:如何使用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 作为测试数据即可。
- 这样,每个测试方法都会使用同一份随机生成的测试数据。
今天关于《如何使用 JUnit5 对同一测试用例的不同排序算法进行测试?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注米云公众号!
