使用hamcrest的Assert.fail等效项

时间:2019-06-26 12:26:39

标签: java unit-testing junit hamcrest

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

2 个答案:

答案 0 :(得分:1)

根据测试的结构方式,我发现使用not(anything())Matchers更自然。

@Test(expected = MyException.class)
public void runMyTestHere() {

    ...

    MyObj result = myService.getThing(id);
    assertThat("Exception should have been thrown.", result, is(not(anything())));
}

答案 1 :(得分:0)

MatcherAssert类具有以下方法:

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

因此,当调用它时,将是最接近的东西:

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