一、JUnit5 簡介
Spring Boot 2.2.0 版本開始引入 JUnit5 作為單元測試默認庫, JUnit5作為最新版本的 JUnit框架, 它與之前版本的 JUnit框架有很大的不同,由三個不同子項目的幾個不同模塊組成.
JUnit5 = JUnitPlatform + JUnitJupiter + JUnitVintage
JUnitPlatform: JUnitPlatform 是在 JVM 上啟動測試框架的基礎,不僅支持 JUnit自制的測試引擎,其它測試引擎也都可以接入.
JUnitJupiter: JUnitJupiter 提供了JUnit5 的新的編程模型,是 JUnit5 新特性的核心.內部包含了一個測試引擎,用於在 JUnitPlatform 上運行.
JUnitVintage: 由於 JUnit已經發展多年,為了照顧老的項目,JUnitVintage 提供了兼容 JUnit 4.x,JUnit 3.x 的測試引擎.
注意:
SpringBoot 2.4 以上版本移除了默認對 Vintage 的依賴.如果需要兼容 JUnit4.x 版本,需要自行引入(不能使用junit4的功能 @Test)
打開項目發布信息 ----> 選擇 v 2.4 這個版本
該版本的變更中說明了已經移除了 JUnit5 了
二、整合 JUnit5
未整合 JUnit 之前
@SpringBootTest + @RunWith(SpringTest.class)
Springboot 整合 Junit 以后
編寫測試方法:@Test標注(注意需要使用 junit5 版本的注解)
Junit類具有 Spring 的功能, 例如 @Autowired、@Transactional (標注測試方法,測試完成后自動回)
我們只需要引入 spring-boot-starter-test 依賴即可完成整合,其它的 Springboot 底層都已經幫我們自動配置好了
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
三、Junit 5 常用注解
具體的使用規范可以參考官網 JUnit 5 官網 https://junit.org/junit5/
JUnit5 的注解與JUnit4 的注解有所變化,具體可以參考官方文檔 https://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations
注解 | 說明 |
@Test | 表示方法是測試方法,但是與 JUnit4 的 @Test 不同,它的職責非常單一不能聲明任何屬性,拓展的測試將會由 Jupiter 提供額外測試 |
@DisplayName | 為測試類或者測試方法設置展示名稱 |
@BeforeAll | 表示在所有單元測試之前執行 |
@BeforeEach | 表示在每個單元測試之前執行 |
@Timeout | 表示測試方法運行如果超過了指定時間將會返回錯誤 |
@Disabled | 表示測試類或測試方法不執行 |
@RepeatedTest | 表示方法可重復執行 |
@ExtendWith | 為測試類或測試方法提供擴展類引用 |
@AfterEach | 表示在每個單元測試之后執行 |
@AfterAll | 表示在所有單元測試之后執行 |
我們就選取幾個測試注解來使用一下
1、測試類
@DisplayName("測試類")
@SpringBootTest
class DatasourceApplicationTests {
@Test
@BeforeAll
public static void beforeAll() {
System.out.println("@BeforeAll: 表示在所有單元測試之前執行");
}
@BeforeEach
public void beforeEach() {
System.out.println("@BeforeEach: 表示在每個單元測試之前執行");
}
@Test
@DisplayName("測試方法一")
public void test01() {
System.out.println("@DisplayName: 為測試類或者測試方法設置展示名稱");
}
@Test
@DisplayName("測試方法二")
@Timeout(value=1,unit=TimeUnit.MICROSECONDS)
public void test02() {
System.out.println("@Timeout: 表示測試方法運行如果超過了指定時間將會返回錯誤");
}
}
2、測試結果
當然 JUnit 5還有很多其它的使用,例如:斷言、前置條件、嵌套測試、參數化測試 以及如何從 Junit 4 遷移到 JUnit 5 等等
在實際開發過程中,建議去參照官方文檔的用戶指南並且結合自身項目的實際情況選擇合適的 JUnit 5 功能