Assert.fail 相当于使用 hamcrest

Assert.fail equivalent using hamcrest

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

MatcherAssertclass有这个方法:

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

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

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

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

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

    ...

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