Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assert equals int long float

Tags:

java

junit

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...

like image 373
Pavel Niedoba Avatar asked Dec 20 '16 12:12

Pavel Niedoba


People also ask

How do you assert long value in JUnit?

You want: assertEquals(42681241600L, 42681241600L); Your code was calling assertEquals(Object, Object). You also needed to append the 'L' character at the end of your numbers, to tell the Java compiler that the number should be compiled as a long instead of an int.

What does assertSame () method use for assertion?

6. What does assertSame() method use for assertion? Explanation: == is used to compare the objects not the content. assertSame() method compares to check if actual and expected are the same objects.

What is assert equals in Java?

assertEquals. public static void assertEquals(Object expected, Object actual) Asserts that two objects are equal. If they are not, an AssertionError without a message is thrown. If expected and actual are null , they are considered equal.

Which assert method is used if you wish to compare primitive datatype values?

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.


Video Answer


1 Answers

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.

like image 193
Mena Avatar answered Oct 16 '22 13:10

Mena