Hamcrest error using either either null or misuse?

I was shocked when something like:

assertThat(null, either(is(nullValue())).or(notNullValue())); 

Failure:

 java.lang.AssertionError: Expected: (is null or not null) but: was null at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20) at org.junit.Assert.assertThat(Assert.java:956) at org.junit.Assert.assertThat(Assert.java:923) at Demo.testName(Demo.java:12) 

I do not think this use is very unusual (I'm actually trying to approve a null or empty card), and I did not find anything wrong with the Hamcrest source code ...

+6
source share
2 answers

It's time for some debugging.

The either() task creates a CombinableMatcher that extends TypeSafeDiagnosingMatcher . The latter automatically rejects null.

IMHO, a parameter of type Matcher is actually just an assumption, not a requirement, so this superclass is really unsafe ...

Edit:

And here is the error report ( https://github.com/hamcrest/JavaHamcrest/issues/49 ). I think this will never be fixed ...

+4
source

use anyOf

From Hamcrest Tutorials

anyOf - matches if matches, short circuits match (for example, Java ||)

Sort of:

 assertThat(value, anyOf(equalTo(1), equalTo(2))); 
+4
source

All Articles