Assert.fail equivalent using hamcrest

Viewed 3019

I use JUnit for Assert.fail but I do not know what is the Hamcrest equivalent. Does anyone know?

2 Answers

The MatcherAssert class has this method:

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

So when invoked it would be the closest thing:

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

Depending on how your test is structured, I found this more natural using the 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())));
}
Related