Search code examples
javajunit4hamcrest

NoSuchMethodError when using assertThat+is with data type short


I have a class, with a public short status, and this line in a test:

assertThat(order.status, is(0));

But it gives me the following error:

java.lang.NoSuchMethodError: org.hamcrest.Matcher.describeMismatch(Ljava/lang/Object;Lorg/hamcrest/Description;)V

    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:18)
    at org.junit.Assert.assertThat(Assert.java:956)
    at org.junit.Assert.assertThat(Assert.java:923)
    at com.example.OrderTest.testStuff(OrderTest.java:101)
    ...

However, if I do the following, which is uglier, the error goes away:

assertThat(order.status, is((short) 0));

What's up with that? 😕


Solution

  • The signature of assertThat() is assertThat(T actual, org.hamcrest.Matcher<T> matcher)

    T in your case is: short

    So you need a Matcher<Short>. But 0 is an int literal. So you have to tell the compiler: use that int value as short.

    Although it would be perfectly fine to turn 0-int into 0-short, Java isn't smart enough. As you are "restricting" something from the int range to short range, you have to put down that cast.