junit 5测试异常处理

JUnit 5带来了令人敬畏的改进,并且与以前的版本有很大不同。 JUnit 5在运行时需要Java 8,因此Lambda表达式可以在测试中使用,尤其是在断言中。 这些断言之一非常适合测试异常。

设置项目

为了演示JUnit 5的用法,我使用了我的长期unit-testing-demo Github项目,因为该项目已经包含许多单元测试示例: https : //github.com/kolorobot/unit-testing-demo 。 向现有项目添加JUnit 5支持非常简单:除了所有标准JUnit 5依赖项之外,在测试运行时路径中还必须存在junit-vintage-engine:

// JUnit 5 Jupiter API and TestEngine implementation
    testCompile("org.junit.jupiter:junit-jupiter-api:5.0.0-M4")
    testRuntime("org.junit.jupiter:junit-jupiter-engine:5.0.0-M4")

    // Support JUnit 4 tests
    testCompile("junit:junit:4.12")
    testRuntime("org.junit.vintage:junit-vintage-engine:4.12.0-M4")

JUnit 5 assertThrows

JUnit 5内置的org.junit.jupiter.api.Assertions#assertThrows获取预期的异常类作为第一个参数,而可执行文件(功能性接口)则可能将异常作为第二个参数。 如果未引发任何异常或其他类型的异常,则该方法将失败。 该方法返回异常本身,该异常可用于进一步的声明:

import org.junit.jupiter.api.*;

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

class Junit5ExceptionTestingTest { // non public, new to JUnit5

    @Test
    @DisplayName("Junit5 built-in Assertions.assertThrows and Assertions.assertAll")
    @Tag("exception-testing")
    void verifiesTypeAndMessage() {
        Throwable throwable = assertThrows(MyRuntimeException.class, new Thrower()::throwsRuntime);

        assertAll(
            () -> assertEquals("My custom runtime exception", throwable.getMessage()),
            () -> assertNull(throwable.getCause())
        );
    }
}

摘要

在JUnit 4中,有许多方法可以测试测试代码中的异常,包括try-catch习惯用法,JUnit @Rule或AssertJ(3+)。 从JUnit 5开始,可以使用内置的断言。

参考资料

翻译自: https://www.javacodegeeks.com/2017/06/testing-exceptions-junit-5.html

junit 5测试异常处理

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐