I am creating a JUnit which is supposed to make each time an array of random size with random integers in it. Afterwards a copy of the array is made and the original array is inputed as a parameter in my mergesort array and gets sorted while the copy of the array gets sorted with the Arrays.sort() method. Then the two arrays are compared to see if they are the same.
Here is the code:
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);
}
}
}
I could clearly see from the println‘s I inserted that only one array was created and the test was running constantly checking that one array but I thought it would create each time a random one which is clearly not the case.
So my question is why is only one array created which I guessed each time the assertArrayEquals(toSort, sorted) run it would the start over again.
I believe it has something to do with the global variables but I’m not quite sure…
If you want this code to function the way you anticipate take the code in your
setupfunction and make it into a new private method that is invoked at the start of each loop like so:Followed by: