JUnit 4 error: reference to assertEquals is ambiguous
This is a somewhat confusing compilation failure that sometimes happen when you write unit tests using JUnit 4. This is an example code snippet that produces this error (result.getValue() returns an Integer object):
And when you try to compile your project it produces a compilation error like this:
/projects/myapp/src/test/java/org/myapp/MyTest.java:[88,8] reference to assertEquals is ambiguous, both method assertEquals(double,double) in org.junit.Assert and method assertEquals(java.lang.Object,java.lang.Object) in org.junit.Assert match
Since JUnit offer several methods that are very similar the compiler can not always determine which one to use. In our case we have the number 12345 which is an int and result.getValue() which is an Integer. You’d think that the compiler could figure out to convert the number 12345 to an Integer object which would give us a match on “assertEquals(java.lang.Object, java.lang.Object) method, but instead it throws the above error.
The reason for this is that Java uses best match to try to determine the method that will require the least conversion of the parameters. In this case one method requires boxing, and the other method would require un-boxing. Both of these methods have equal priority and that’s why there is ambiguity since none of the methods are more specific than the other.
The solution is to help the compiler determine what it need to do. We can do that using this:
assertEquals(12345, (int) result.getValue());
to resolve this problem. The second solution that converts 12345 to an Integer object is most likely the better once since Java will auto-box a null value to the number 0 which may not be the correct behavior for the class you’re testing.