【问题标题】:Why doesn't this assert work - assertThat(foo, is(not(null)));为什么这个断言不起作用 - assertThat(foo, is(not(null)));
【发布时间】:2014-12-16 04:04:29
【问题描述】:

即使我知道 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;

...

assertThat(foo, is(not(null)));

【问题讨论】:

    标签: java hamcrest


    【解决方案1】:

    根据经验,我发现这是可行的:

    assertThat(foo, is(not(nullValue())));
    

    【讨论】:

    • 甚至有自己的方法:Matchers.notNullValue()
    • 感谢您告诉我@eee
    【解决方案2】:

    tl;dr

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

        assertThat(foo, notNullValue());
    

    快捷方式:

    import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.Matchers.notNullValue;
        ...
        assertThat(foo, notNullValue());
    

    感谢@eee

    规范形式:

    import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.Matchers.not;
    import static org.hamcrest.Matchers.nullValue;
        ...
        assertThat(foo, not( nullValue() ));
    

    您的 (OP) 方法:

    import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.Matchers.not;
        ...
        assertThat(foo, not( (Foo)null ));
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多