Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is assertEquals(Object[], Object[]) from JUnit 4 deprecated?

Tags:

java

junit

assert

Eclipse is giving me a warning that says that the method assertEquals(Object[], Object[]) from the type Assert is deprecated. I am using JUnit 4.

I wrote the following code in Eclipse:

import org.junit.Test;
import org.junit.Assert;

public class Generics { 
    public <T> T[] genericArraySwap(T[] list, int pos1, int pos2) throws IndexOutOfBoundsException {
        ...
    }

    @Test
    public void genericArraySwapTest() {
        Integer[] IntegerList = {0, 1, 2, 3, 4};        
        Assert.assertEquals(new Integer[] {0, 1, 2, 4, 3}, genericArraySwap(IntegerList, 3, 4));
    }
}

Can someone tell me why this method is deprecated or what method I should use instead?

like image 718
karposhark Avatar asked Feb 01 '17 19:02

karposhark


1 Answers

It's deprecated because of the lack of expressivity of the Java type system.

Whereas all of the other assertEquals methods will compare the parameters using == (for primitives) or equals (for reference types), you don't want to use either to compare arrays: all arrays are subtypes of Object (i.e. they are reference types), and don't override equals, so using assertEquals to compare arrays will check whether the two arrays are identical.

Instead, you should invoke assertArrayEquals, which compares whether the arrays have the same length, and if so, whether the corresponding array elements are equal.

Ideally, you would be able to specify parameter types like this:

assertEquals(T, T)

where T is "any subtype of Object, except for arrays". But you simply can't do that in Java; even if there were a way to express such a constraint, you couldn't prevent the method being called with array, because you can always upcast them to Objects.

The only thing that you can do is to:

  • Provide an overload which accepts Objects
  • Provide overloads which accept more specific types, and mark these overloads @Deprecated. To cover all array types, you need 9 overloads (8 for each of the primitive array types; 1 for Object[], which covers all other reference types).

This doesn't prevent you from invoking assertEquals(T[], T[]), but it does highlight that there is a problem there, via compiler warnings; yellow squiggles in Eclipse; etc.

Of course, this won't help in the case that you've upcast the arrays to Object; but you won't, in most cases, unless you really intend to invoke that specific method.

like image 182
Andy Turner Avatar answered Nov 06 '22 05:11

Andy Turner