Ambiguous method call Both assertEquals(Object, Object) in Assert and assertEquals(double, double) in Assert match:

JavaObjectJunitDoubleAssert

Java Problem Overview


I am getting the following error:

Both assertEquals(Object, Object) in Assert and assertEquals(double, double) in Assert match

For this line of code in my Junit tests, note that getScore() returns a double:

assertEquals(2.5, person.getScore());

This is my assert import:

import static org.junit.Assert.*;

What is causing this and how can I fix this?

Java Solutions


Solution 1 - Java

Your getScore() returns Double, not double. Therefore compiler is confused: Should it convert both arguments to Object, or if it should convert only the Double to double?

    double a = 2.0;
    Double b = 2.0;
    // assertEquals(a,b); // fails to compile
    // the compiler is confused whether to use
    assertEquals((Object) a,(Object) b); // OK
    // or
    assertEquals(a,(double) b); // OK

Anyway, I would set the method to return primitive type double.

Solution 2 - Java

If you specifically interested in using Assert.assertEquals(double, double) (the primitive version), try calling overridden method that allows deviation and setting allowed deviation to zero, like this:

assertEquals(2.5, person.getScore(), 0.0);

You might also want to have third parameter to be something other than zero if person.getScore() is allowed to be slightly different from 2.5. For example, if 2.500001 is acceptable, then your test becomes

assertEquals(2.5, person.getScore(), 0.000001);

Solution 3 - Java

If you specifically want to avoid casting AND use the primitive version, you can get the primitive result from a wrapper object. For example:

    double a = 2.0;
    Double b = 2.0;
    assertEquals(a, b.doubleValue()); //Deprecated so use the one with delta

    Integer c = 2;
    int d = 2;
    assertEquals(c.intValue(), d);

    Long e = 2L;
    long f = 2L;
    assertEquals(e.longValue(), f);

Solution 4 - Java

I had the same error, I changed from this:

assertEquals("Server status code is: " +  wmResp.getStatusCode() , 200, wmResp.getStatusCode());

To this

assertEquals("Server status code is: " +  wmResp.getStatusCode() , Integer.valueOf(200), wmResp.getStatusCode());

This is happening because the first line compiler takes the 200 as primitive (integer not Integer class)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionjava123999View Question on Stackoverflow
Solution 1 - JavaBechyňák PetrView Answer on Stackoverflow
Solution 2 - JavaM. ProkhorovView Answer on Stackoverflow
Solution 3 - JavaMolten IceView Answer on Stackoverflow
Solution 4 - JavaJavaSheriffView Answer on Stackoverflow