【问题标题】:Assert.fail equivalent using hamcrest使用 hamcrest 的 Assert.fail 等效项
【发布时间】:2019-06-26 12:26:39
【问题描述】:

我将 JUnit 用于 Assert.fail,但我不知道 Hamcrest 的等价物是什么。有人知道吗?

【问题讨论】:

    标签: java unit-testing junit hamcrest


    【解决方案1】:

    MatcherAssert 类有这个方法:

    public static void assertThat(String reason, boolean assertion) {
        if (!assertion) {
            throw new AssertionError(reason);
        }
    }
    

    所以当被调用时,它将是最接近的东西:

    MatcherAssert.assertThat("Fail here", false);
    

    【讨论】:

      【解决方案2】:

      根据您的测试结构,我发现使用 not(anything()) 匹配器更自然。

      @Test(expected = MyException.class)
      public void runMyTestHere() {
      
          ...
      
          MyObj result = myService.getThing(id);
          assertThat("Exception should have been thrown.", result, is(not(anything())));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-08
        • 2011-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多