Hamcrest bug with either-or and null or incorrect usage?
Asked Answered
C

2

8

I was shocked when something along the lines of:

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

Fails with:

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 don't think this usage is very unusual (I am actually trying to assert null or empty map) and I couldn't find anything wrong with the Hamcrest source code...

Clinandrium answered 24/9, 2015 at 10:59 Comment(0)
T
5

use anyOf

From Hamcrest tutorials

anyOf - matches if any matchers match, short circuits (like Java ||)

Something like:

assertThat(value, anyOf(equalTo(1), equalTo(2)));
Tallyho answered 24/9, 2015 at 11:6 Comment(0)
C
4

Had some time to do some debugging.

The problem is either() generates a CombinableMatcher which extends TypeSafeDiagnosingMatcher. The latter automatically rejects null.

IMHO, the type parameter of Matcher is really just a suggestion rather than a requirement so this super class is really unsafe...

Edit:

And here's a bug report (https://github.com/hamcrest/JavaHamcrest/issues/49). I guess it will never get fixed...

Clinandrium answered 24/9, 2015 at 12:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.