Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hamcrest bug with either-or and null or incorrect usage?

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...

like image 687
billc.cn Avatar asked Sep 24 '15 10:09

billc.cn


People also ask

What is a valid Hamcrest assert statement?

Asserting That Two Objects or Values Are Equal If we want to verify that the expected value (or object) is equal to the actual value (or object), we have to create our Hamcrest matcher by invoking the equalTo() method of the Matchers class.

What is the use of Hamcrest dependency?

Hamcrest is the well-known framework used for unit testing in the Java ecosystem. It's bundled in JUnit and simply put, it uses existing predicates – called matcher classes – for making assertions.

What is the use of Hamcrest jar?

hamcrest-core. jar : This was the core API to be used by third-party framework providers. This includes a foundation set of matcher implementations for common operations. This library was used as a dependency for many third-party libraries, including JUnit 4.

Is assertThat actual is equalTo expected ))) a valid Hamcrest assert statement?

assertEquals() is the method of Assert class in JUnit, assertThat() belongs to Matchers class of Hamcrest. Both methods assert the same thing; however, hamcrest matcher is more human-readable. As you see, it is like an English sentence “Assert that actual is equal to the expected value”.


1 Answers

use anyOf

From Hamcrest tutorials

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

Something like:

assertThat(value, anyOf(equalTo(1), equalTo(2)));
like image 158
thegauravmahawar Avatar answered Oct 26 '22 23:10

thegauravmahawar