我正在创建一个 JUnit,它应该每次都生成一个随机大小的数组,其中包含随机整数。然后制作数组的副本,并将原始数组作为参数输入到我的合并排序数组中并进行排序,而数组的副本则使用该Arrays.sort()
方法进行排序。然后比较这两个数组,看它们是否相同。
这是代码:
import java.util.Arrays;
import java.util.Random;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Before;
import org.junit.Test;
public class Mergesort_3wayTest {
private int[] toSort;
private static int SIZE;
private static int MAX;
private static int tests = 20000;
@Before
public void setUp() throws Exception {
Random generator = new Random();
SIZE = generator.nextInt(30) + 1;
MAX = generator.nextInt(30) + 1;
toSort = new int[SIZE];
for (int i = 0; i < toSort.length; i++) {
toSort[i] = generator.nextInt(MAX);
}
}
@Test
public void itWorksRepeatably() {
for (int i = 0; i < tests; i++) {
System.out.println("1 - " + Arrays.toString(toSort));
int[] sorted = new int[toSort.length];
System.arraycopy(toSort, 0, sorted, 0, toSort.length);
Arrays.sort(sorted);
Mergesort_3way.mergesort(toSort);
System.out.println("2 - " + Arrays.toString(toSort));
assertArrayEquals(toSort, sorted);
}
}
}
我可以从println
我插入的 's 中清楚地看到,只创建了一个数组,并且测试正在不断地检查那个数组,但我认为它每次都会创建一个随机数组,但显然不是这样。
所以我的问题是为什么只创建一个数组,我猜每次assertArrayEquals(toSort, sorted)
运行它都会重新开始。
我相信它与全局变量有关,但我不太确定......