使用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 implementationtestCompile("org.junit.jupiter:junit-jupiter-api:5.0.0-M4")testRuntime("org.junit.jupiter:junit-jupiter-engine:5.0.0-M4")// Support JUnit 4 teststestCompile("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獲取預期的異常類作為第一個參數,而可執行文件(功能接口)則可能將異常作為第二個參數。 如果未引發任何異?;蚱渌愋偷漠惓?#xff0c;則該方法將失敗。 該方法返回異常本身,該異常可用于進一步的聲明:
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開始,可以使用內置的斷言。
參考文獻
- 測試異常– JUnit 4和AssertJ
- 測試異常– JUnit 4,Java 8和Lambda表達式
- 在JUnit中測試異常的不同方法
翻譯自: https://www.javacodegeeks.com/2017/06/testing-exceptions-junit-5.html
總結
以上是生活随笔為你收集整理的使用JUnit 5测试异常的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电话报警会备案吗(电话报警会备案吗)
- 下一篇: 什么是JAX-RS注释? (第3部分)