assert equals int long float
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.
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.