首页 > 解决方案 > JUnit5 - ExpectedException.expectCause() 等效

问题描述

是否有ExpectedException.expectCause()(JUnit4) 的 JUnit5 等价物? https://junit.org/junit4/javadoc/4.12/org/junit/rules/ExpectedException.html#expectCause(org.hamcrest.Matcher)

标签: junit5

解决方案


这是一个例子:

public class ExpectedExceptionTest {

    @Test
    public void shouldThrow() {
        IOException exc = Assertions.assertThrows(IOException.class, this::throwing);
        Assertions.assertEquals("root cause", exc.getCause().getMessage());
    }

    private void throwing() throws IOException {
        throw new IOException(new IllegalStateException("root cause"));
    }
}

就个人而言,我更喜欢 AssertJ,它具有非常描述性的异常断言


推荐阅读