30

Is there an elegant way to assert numbers are equal while ignoring their classes? I want to use it in JUnit tests framework but for example

Assert.assertEquals(1,1L)

fails with java.lang.AssertionError: expected: java.lang.Integer<1> but was: java.lang.Long<1>

I expect there is a nice method somewhere which compares only value and works with int, long, float, byte, double, BigDecimal, BigInteger, you name it...

10
  • 2
    Why is this downvoted? Seems like a legit question to me.
    – Mena
    Dec 20, 2016 at 12:16
  • 1
    I agree. Have an upvote! I also think the answer is not trivial.
    – Bathsheba
    Dec 20, 2016 at 12:17
  • I was thinking about Number.toString.equals, but there is scientific format to deal with Dec 20, 2016 at 12:18
  • For primitives, you can create overloads assertEquals(int, int), assertEquals(long, long), assertEquals(float, float) etc, which all call Assert.assertEquals(a, b), and overload resolution will pick the appropriate one. You might well get ambiguous overload problems in some cases. I think that doing it for Big* against primitives might get trickier though. I'd question exactly why you really want this - how frequently are the operands of different types? Dec 20, 2016 at 12:19
  • 3
    If I run that piece of code, it just works fine... (Java 8, Junit 4.11) maybe Assert.assertThat(1, is(1L)); might also help you... You may need to implement your own Matcher then...
    – Roland
    Dec 20, 2016 at 12:22

5 Answers 5

15

One workaround with some overhead would be to wrap the values in BigDecimal objects, as BigDecimal constructor overloads take long, int and double primitives.

Since new BigDecimal(1l).equals(new BigDecimal(1.0)) holds true,

Assert.assertEquals(new BigDecimal(1.0), new BigDecimal(1l));  

should work for you.

Edit

As Hulk states below, the scale of the BigDecimal objects is used in the equals comparison, but not in the compareTo comparison. While the scale is set to a default 0 for the constructor taking long, it is inferred through some calculation in the constructor taking double. Therefore the safest way to compare values (i.e. in edge cases for double values) might be through invoking compareTo and checking the outcome is 0 instead.

7
  • 1
    I accept this because it is elegant one line solution Dec 20, 2016 at 20:36
  • @PavelNiedoba cheers. Watch out about the overhead though, you are creating objects everytime.
    – Mena
    Dec 20, 2016 at 20:38
  • 2
    Obligatory caution when using equals to compare BigDecimals: It is inconsistent with compareTo in that it also takes scale into account, JavaDocs of BigDecimal.equals see also stackoverflow.com/q/6787142
    – Hulk
    Dec 21, 2016 at 9:56
  • @Hulk good point. Maybe comparing doubleValue from the BigDecimals instead might be less error prone? I see that the scale is calculated, at least in the BigDecimal(double) constructor, so I'm wondering whether it might differ indeed at times when initializing as above...
    – Mena
    Dec 21, 2016 at 10:01
  • 1
    @Hulk or otherwise just use compareTo I guess, no need to make things harder :)
    – Mena
    Dec 21, 2016 at 10:02
10

According to my reading of the JLS, the overload resolution for

Assert.assertEquals(1,1L)

should resolve to

Assert.assertEquals(long, long)

In short, the code snippet in the question is not a valid example of your actual problem.

(For the record, assertEquals(long, long), assertEquals(float, float) and assertEquals(double, double) are applicable by strict invocation, and the first one is the most specific; see JLS 15.12.2.2. The strict invocation context allows primitive widening, but not boxing or unboxing.)

If (as the evidence suggests) your call is resolving to Assert.assertEquals(Object, Object), that implies that one of the operands must already be a boxed type. The problem with that overload is that it is using the equals(Object) method to compare objects, and the contract for that method specifies that the result is false if the objects' respective types are different.

If that is what is going on in your real code, then I doubt that the suggestion of using the is(T) Matcher will work either. The is(T) matcher is equivalent to is(equalTo(T)) and the latter relies on equals(Object) ...

Is there an existing "nice method"?

AFAIK, no.

I think that the real solution is to be a bit more attentive to the types; e.g.

 int i = 1;
 Long l = 1L;
 Assert.assertEquals(i, l);         // Fails
 Assert.assertEquals((long) i, l);  // OK - assertEquals(Object, Object)
 Assert.assertEquals((Long) i, l);  // OK - assertEquals(Object, Object)
 Assert.assertEquals(i, (int) l);   // OK - assertEquals(long, long) 
                                    //      it would bind to an (int, int) 
                                    //      overload ... it it existed.   
 Assert.assertEquals(i, (long) l);  // OK - assertEquals(long, long)


 

Writing a custom Matcher would work too.

0
4

Wrap that functionality in your own Matcher and use it with assertThat.

Sample matcher:

class IsAnyNumber extends BaseMatcher {
  final Object expected;
  //...
  public boolean matches(Object actual) {
    // compare / transform / check type / ensure: String, double, int, long
    // example via BigDecimal as seen from Mena (without checks)
    return new BigDecimal(expected).equals(new BigDecimal(actual));
  }
  // ...
}

// somewhere else:
public static IsAnyNumber is(Object expected) {
  return new IsAnyNumber(expected);
}

In your tests you then call that static method:

assertThat(1, is(1L));
assertThat(1, is(1.0));
assertThat(1L, is(1));

This way you can reuse your matcher and the assert statement is more readable in the end.

Disclaimer: this is only pseudo-code and was not yet tested, but should work with some tweaking.

But beware also from Comparing Numbers in Java

1

Create your own assert methods and compare the double values for the primitives. If a BigDecimal is used, the primitive value has to be converted to a BigDecimal

static void assertEquals(Number number1, Number number2) {
  Assert.assertEquals(number1.doubleValue(), number2.doubleValue());
}

static void assertEquals(BigDecimal number1, BigDecimal number2) {
  if (number2.compareTo(number1) != 0) {
    Assert.fail("Values are not equal. ..... ");
  }
}

static void assertEquals(Number number1, BigDecimal number2) {
  assertEquals(new BigDecimal(number1.doubleValue()), number2);
}

static void assertEquals(BigDecimal number1, Number number2) {
  assertEquals(number2, number1);
}

It can be used this way:

assertEquals(1, new BigDecimal("1.0"));
assertEquals(1.0d, 1);
assertEquals(new Float(1.0f), 1.0d);
assertEquals(new BigDecimal("1.00000"), new BigDecimal("1.0"));
...
0

I think to accept all eight types of numerical values (primitive and object), the method has to take string arguments. The caller will have to remember to cast the value to string by this idiom:

""+value

Also, in case the value is not an integer (int, Integer, long, Long) but a floating point representation (float, double, Float, Double), the method must also take a argument epsilon to tolerate imprecision due to the representation.

So here is an implementation idea (for now I ignore the cases of NaN and positive and negative zeros of double -- these can be added if a truly solid implementation is needed)

private static boolean equalsNumerically(String n1String
                                        , String n2String
                                        , double epsilon) {
    try {
        Long n1Long = new Long(n1String);
        Long n2Long = new Long(n2String);
        return n1Long.equals(n2Long);
    } catch (NumberFormatException e) {
        /*
         * If either one of the number is not an integer, try comparing
         * the two as Double
         */
        try {
            Double n1Double = new Double(n1String);
            Double n2Double = new Double(n2String);
            double delta = ( n1Double - n2Double) / n2Double;
            if (delta<epsilon) {
                return true;
            } else {
                return false;
            }
        } catch (NumberFormatException e2) {
            return false;
        }
    } 
}

Testing code

    int     primitiveInt = 1;
    long    primitiveLong = 1L;
    float   primitiveFloat = 0.999999F;
    double  primitiveDouble = 0.999999D;
    Integer objectInt = new Integer(1);
    Long    objectLong = new Long(1);
    Float   objectFloat = new Float(0.999999);
    Double  objectDouble = new Double(0.999999);

    final double epsilon = 1E-3;

    Assert.assertTrue(equalsNumerically(""+primitiveInt, ""+primitiveLong, 0)); 
    System.out.format("Test passed: "
            + "Assert.assertTrue(equalsNumerically(\"\"+primitiveInt"
            + ", \"\"+primitiveLong, 0): %s %s %s%n"
            , primitiveInt, primitiveLong, epsilon);

    Assert.assertTrue(equalsNumerically(""+primitiveInt, ""+primitiveLong, epsilon));
    System.out.format("Test passed: "
            + "Assert.assertTrue(equalsNumerically(\"\"+primitiveInt"
            + ", \"\"+primitiveLong, epsilon)): %s %s %s%n"
            , primitiveInt, primitiveLong, epsilon);

    Assert.assertTrue(equalsNumerically(""+primitiveInt, ""+primitiveFloat, epsilon)); 
    System.out.format("Test passed: "
            + "Assert.assertTrue(equalsNumerically(\"\"+primitiveInt"
            + ", \"\"+primitiveFloat, 0): %s %s %s%n"
            , primitiveInt, primitiveFloat, epsilon);

    Assert.assertTrue(equalsNumerically(""+primitiveInt, ""+primitiveDouble, epsilon)); 
    System.out.format("Test passed: "
            + "Assert.assertTrue(equalsNumerically(\"\"+primitiveInt"
            + ", \"\"+primitiveDouble, epsilon): %s %s %s%n"
            , primitiveInt, primitiveDouble, epsilon);

    Assert.assertTrue(equalsNumerically(""+primitiveInt, ""+objectInt, 0)); 
    System.out.format("Test passed: "
            + "Assert.assertTrue(equalsNumerically(\"\"+primitiveInt"
            + ", \"\"+objectInt, 0): %s %s %s%n"
            , primitiveInt, objectInt, epsilon);

    Assert.assertTrue(equalsNumerically(""+primitiveInt, ""+objectLong, 0)); 
    System.out.format("Test passed: "
            + "Assert.assertTrue(equalsNumerically(\"\"+objectLong"
            + ", \"\"+objectLong, 0): %s %s %s%n"
            , primitiveInt, primitiveLong, epsilon);

    Assert.assertTrue(equalsNumerically(""+primitiveInt, ""+objectFloat, epsilon));
    System.out.format("Test passed: "
            + "Assert.assertTrue(equalsNumerically(\"\"+primitiveInt"
            + ", \"\"+objectFloat, epsilon)): %s %s %s%n"
            , primitiveInt, objectFloat, epsilon);

    Assert.assertTrue(equalsNumerically(""+primitiveInt, ""+objectDouble, epsilon)); 
    System.out.format("Test passed: "
            + "Assert.assertTrue(equalsNumerically(\"\"+primitiveInt"
            + ", \"\"+objectDouble, 0): %s %s %s%n"
            , primitiveInt, objectDouble, epsilon);

Test output

Test passed: Assert.assertTrue(equalsNumerically(""+primitiveInt, ""+primitiveLong, 0): 1 1 0.001
Test passed: Assert.assertTrue(equalsNumerically(""+primitiveInt, ""+primitiveLong, epsilon)): 1 1 0.001
Test passed: Assert.assertTrue(equalsNumerically(""+primitiveInt, ""+primitiveFloat, 0): 1 0.999999 0.001
Test passed: Assert.assertTrue(equalsNumerically(""+primitiveInt, ""+primitiveDouble, epsilon): 1 0.999999 0.001
Test passed: Assert.assertTrue(equalsNumerically(""+primitiveInt, ""+objectInt, 0): 1 1 0.001
Test passed: Assert.assertTrue(equalsNumerically(""+primitiveInt, ""+objectLong, 0): 1 1 0.001
Test passed: Assert.assertTrue(equalsNumerically(""+primitiveInt, ""+objectFloat, epsilon)): 1 0.999999 0.001
Test passed: Assert.assertTrue(equalsNumerically(""+primitiveInt, ""+objectDouble, 0): 1 0.999999 0.001
1
  • Better to use String.valueOf(value) then ""+value. Because it is cleaner and more understandable. Feb 13, 2020 at 9:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.