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

限于喜欢 提交于 2019-12-01 16:59:43

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:

assertThat(longValue, greaterThan(1));
assertThat(longList, contains(1, 2, 3));

Update

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

public static Matcher<Long> is(Integer value) {
    return org.hamcrest.core.Is.is(value.longValue());
}

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

public static Matcher<Long> is(Float value) {
    return org.hamcrest.core.Is.is(value.longValue());
}

public static Matcher<Long> is(Double value) {
    return org.hamcrest.core.Is.is(value.longValue());
}

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?

public static Matcher<Double> is(Integer value) {
    return org.hamcrest.core.Is.is(value.doubleValue());
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!