How do you assert that a certain exception is thrown in JUnit 4 tests?

前端 未结 30 1928
忘掉有多难
忘掉有多难 2020-11-21 22:23

How can I use JUnit4 idiomatically to test that some code throws an exception?

While I can certainly do something like this:

@Test
public void testFo         


        
30条回答
  •  无人共我
    2020-11-21 23:19

    Junit4 solution with Java8 is to use this function:

    public Throwable assertThrows(Class expectedException, java.util.concurrent.Callable funky) {
        try {
            funky.call();
        } catch (Throwable e) {
            if (expectedException.isInstance(e)) {
                return e;
            }
            throw new AssertionError(
                    String.format("Expected [%s] to be thrown, but was [%s]", expectedException, e));
        }
        throw new AssertionError(
                String.format("Expected [%s] to be thrown, but nothing was thrown.", expectedException));
    }
    

    Usage is then:

        assertThrows(ValidationException.class,
                () -> finalObject.checkSomething(null));
    

    Note that the only limitation is to use a final object reference in lambda expression. This solution allows to continue test assertions instead of expecting thowable at method level using @Test(expected = IndexOutOfBoundsException.class) solution.

提交回复
热议问题