JUnit asserting arrays are equal when they're not

arrays, java, junit

Solution

The problem is right here:

Integer[] correctArray = TestArray;

You're copying the reference to your array, not the contents of the array.

To fix, change that line to:

Integer[] correctArray = TestArray.clone();

Problem

I have a mergesort function I am testing using JUnit. Below is one of my test cases: ``` @Test //test using randomly generated numbers public void MergeSortTest002() { long seed = System.currentTimeMillis(); Random rng = new Random(seed); Integer[] TestArray = new Integer[1000]; int MAX_VALUE = Integer.MAX_VALUE; for(int i=0; i<1000; i++) { //this will generate positive and negative numbers from // -MAX_VALUE/2 to +MAX_VALUE/2 Integer newNum = rng.nextInt(MAX_VALUE/2) - MAX_VALUE; TestArray[i] = newNum; } Integer[] correctArray = TestArray; Arrays.sort(correctArray); MergeSort.mergeSort(TestArray); Assert.assertArrayEquals(correctArray,TestArray); } ``` The strange thing is, even if I comment out the line where I call my `mergeSort` function, the test still passes. I figured one of two things is happening: Either `assertArrayEquals` does not care about the order of elements (unlikely), of when I'm copying `TestArray` to `correctArray`, it's copying by reference, and thus calling `Arrays.sort` on `correctArray` is sorting `TestArray` as well. Could anyone confirm which of the two is happening, and what should be the solution? Is there a `Assert` that keeps order in mind, or is there a way to copy arrays by values rather than reference without writing an explicit for loop?

Original source