This assertion compiles but fails even though I know for a fact that foo is not null:
import static org.hamcrest.Matchers.is; // see http://stackoverflow.com/a/27256498/2848676
import static org.hamcrest.Matchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
...
assertThat(foo, is(not(null)));
The assertThat is one of the JUnit methods from the Assert object that can be used to check if a specific value match to an expected one. It primarily accepts 2 parameters. First one if the actual value and the second is a matcher object.
assertThat method is deprecated. Its sole purpose is to forward the call to the MatcherAssert. assertThat method defined in Hamcrest 1.3. Therefore, it is recommended to directly use the equivalent assertion defined in the third party Hamcrest library.
Assert. assertNotNull() methods checks that the object is null or not. If it is null then it throws an AssertionError.
Assert class in case of JUnit 4 or JUnit 3 to assert using assertNull method. Assertions. assertNull() checks that object is null. In case, object is not null, it will through AssertError.
Empirically, I've found that this works instead:
assertThat(foo, is(not(nullValue())));
your assert doesn't work, because you call not(Matcher<T> matcher)
with null
matcher. Use a sortcut, instead:
assertThat(foo, notNullValue());
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
...
assertThat(foo, notNullValue());
credits to @eee
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
...
assertThat(foo, not( nullValue() ));
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
...
assertThat(foo, not( (Foo)null ));
The type casting is required here, in order to don't confuse not(T value)
with not(Matcher<T> matcher)
.
REF: http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html
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