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...
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.
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.
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.
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”.
use anyOf
From Hamcrest tutorials
anyOf - matches if any matchers match, short circuits (like Java ||)
Something like:
assertThat(value, anyOf(equalTo(1), equalTo(2)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With