Skip to content
Advertisement

How to use (primitive) autoboxing/widening with Hamcrest?

I came across https://code.google.com/p/hamcrest/issues/detail?id=130 to add some sugar syntax for Hamcrest matchers. But the idea was rejected by the Hamcrest developers.

Any other smart ideas to make tests better readable by avoiding having to type L behind longs?

JavaScript

UPDATE

See also below the differences when comparing e.g. int and long using default Java laguage (==), standard junit assert (assertTrue) and the hamcrest is() method. It seems odd hamcrest doest not supporting matching/comparing long vs int and the rest is.

JavaScript

Advertisement

Answer

This is totally unrelated to the issue you linked which is about addressing faulty static analyzers and was correctly rejected. The issue you’re experiencing is common in Java when mixing primitive types.

To avoid typing that L you’d have to provide overloaded versions of all the matchers–not just is. Consider these examples:

JavaScript

Update

You can easily add your own overloaded versions to perform the conversion:

JavaScript

Of course, now that you have one to convert from int to long you’ll want ones for float and double:

JavaScript

Since Java won’t automatically convert from byte to Integer*, you also needs versions for byte and short. That’s ugly enough, but what about casting to the other types, e.g., from int to double?

JavaScript

Compile Error: Duplicate method is(Integer)

Uh oh! These won’t work because Java doesn’t allow you to overload methods based on the return type. You’ll have to declare these methods in separate classes which I leave to you.

Given the giant mess this would create, I doubt the Hamcrest authors would be open to such an addition given the low payoff. Honestly, you’re much better off being explicit by using 1L and 1.0 as needed.

* Though the compiler will convert from byte to int which could be boxed to Integer.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement