flamecto flamecto - 1 month ago 9
Java Question

Why does junit4 not have Assert.assertArrayEquals() for String array?

From the junit4 documentation for Assert, there is no method for

assertArrayEquals(String[] expecteds, String[] actuals)
. The closest one is
assertArrayEquals(Object[] expecteds, Object[] actuals)
. Why is this the case?

I'm writing my test in Scala, and am currently working around it with Array.sameElements(). Is this a good way to do the comparison?

Answer

assertArrayEquals(Object[] expecteds, Object[] actuals) is a common method which can be used even for String[] array comparisons as String already override equals(), for example you can refer the below code:

    @Test
    public void test() {
        String[] s1 = {"A", "B"};
        String[] s2 = {"A", "B"};
        Assert.assertArrayEquals(s1, s2); //test passes
    } 

assertArrayEquals(Object[] expecteds, Object[] actuals) method internally uses Arrays.deepEquals() as below:

static boolean deepEquals0(Object e1, Object e2) {
        assert e1 != null;
        boolean eq;
        if (e1 instanceof Object[] && e2 instanceof Object[])
            eq = deepEquals ((Object[]) e1, (Object[]) e2);
        else if (e1 instanceof byte[] && e2 instanceof byte[])
            eq = equals((byte[]) e1, (byte[]) e2);
        else if (e1 instanceof short[] && e2 instanceof short[])
            eq = equals((short[]) e1, (short[]) e2);
        else if (e1 instanceof int[] && e2 instanceof int[])
            eq = equals((int[]) e1, (int[]) e2);
        else if (e1 instanceof long[] && e2 instanceof long[])
            eq = equals((long[]) e1, (long[]) e2);
        else if (e1 instanceof char[] && e2 instanceof char[])
            eq = equals((char[]) e1, (char[]) e2);
        else if (e1 instanceof float[] && e2 instanceof float[])
            eq = equals((float[]) e1, (float[]) e2);
        else if (e1 instanceof double[] && e2 instanceof double[])
            eq = equals((double[]) e1, (double[]) e2);
        else if (e1 instanceof boolean[] && e2 instanceof boolean[])
            eq = equals((boolean[]) e1, (boolean[]) e2);
        else
            eq = e1.equals(e2);//non primitives
        return eq;
    }

So, non-primites are compared using equals() for each element inside the object array.