assert equals int long float

Pavel Niedoba :

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

Mena :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=447493&siteId=1