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...
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With