5.6 JUnit 5:如何断言一个异常是否被抛出? | Java Debug 笔记

1,782 阅读1分钟

本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看<活动链接>

提问:JUnit 5:如何断言一个异常是否被抛出?

有没有更好的方法来断言方法会在JUnit 5中引发异常?

当前,我必须使用@Rule来验证我的测试引发异常,但这不适用于我期望多种方法在测试中引发异常的情况。

回答:

您可以使用assertThrows(),它允许您在同一测试中测试多个异常。自从有了Java 8中对lambda的支持,这就是在JUnit中测试异常的规范方法。

+200
您可以使用assertThrows(),它允许您在同一测试中测试多个异常。有了Java 8中对lambda的支持,这是在JUnit中测试异常的规范方法。

根据JUnit文档:

import static org.junit.jupiter.api.Assertions.assertThrows;

@Test
void exceptionTesting() {
    MyException thrown = assertThrows(
           MyException.class,
           () -> myObject.doThing(),
           "Expected doThing() to throw, but it didn't"
    );

    assertTrue(thrown.getMessage().contains("Stuff"));
}

回答2:

现在,Junit5提供了断言异常的方法

您可以测试常规异常和自定义异常

一般的异常情况:

ExpectGeneralException.java


public void validateParameters(Integer param ) {
    if (param == null) {
        throw new NullPointerException("Null parameters are not allowed");
    }
}

ExpectGeneralExceptionTest.java

@Test
@DisplayName("Test assert NullPointerException")
void testGeneralException(TestInfo testInfo) {
    final ExpectGeneralException generalEx = new ExpectGeneralException();

     NullPointerException exception = assertThrows(NullPointerException.class, () -> {
            generalEx.validateParameters(null);
        });
    assertEquals("Null parameters are not allowed", exception.getMessage());
}

您可以在此处找到测试CustomException的示例:

ExpectCustomException.java

public String constructErrorMessage(String... args) throws InvalidParameterCountException {
    if(args.length!=3) {
        throw new InvalidParameterCountException("Invalid parametercount: expected=3, passed="+args.length);
    }else {
        String message = "";
        for(String arg: args) {
            message += arg;
        }
        return message;
    }
}

ExpectCustomExceptionTest.java



@Test
@DisplayName("Test assert exception")
void testCustomException(TestInfo testInfo) {
    final ExpectCustomException expectEx = new ExpectCustomException();

     InvalidParameterCountException exception = assertThrows(InvalidParameterCountException.class, () -> {
            expectEx.constructErrorMessage("sample ","error");
        });
    assertEquals("Invalid parametercount: expected=3, passed=2", exception.getMessage());
}