为什么这个断言不起作用 - assertThat(foo, is(not(null)));

Mic*_*sky 7 java hamcrest

即使我知道 foo 不为空这一事实,该断言也能编译但失败:

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;
Run Code Online (Sandbox Code Playgroud)

...

assertThat(foo, is(not(null)));
Run Code Online (Sandbox Code Playgroud)

Mic*_*sky 10

根据经验,我发现这可以代替:

assertThat(foo, is(not(nullValue())));
Run Code Online (Sandbox Code Playgroud)

  • 甚至有一个自己的方法:`Matchers.notNullValue()`。 (7认同)

epo*_*pox 10

太长了;博士

你的断言不起作用,因为你not(Matcher<T> matcher)null匹配器调用。请改用排序:

    assertThat(foo, notNullValue());
Run Code Online (Sandbox Code Playgroud)

快捷方式:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
    ...
    assertThat(foo, notNullValue());
Run Code Online (Sandbox Code Playgroud)

致谢@eee

规范形式:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
    ...
    assertThat(foo, not( nullValue() ));
Run Code Online (Sandbox Code Playgroud)

你的(OP)方法:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
    ...
    assertThat(foo, not( (Foo)null ));
Run Code Online (Sandbox Code Playgroud)

这里需要进行类型转换,以免not(T value)not(Matcher<T> matcher). 参考:http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html