JUnit5
SpringBoot 2.4 以上版本移除了默認對 Vintage 的依賴。如果需要兼容junit4需要自行引入(不能使用junit4的功能 @Test)
JUnit 5’s Vintage Engine Removed from spring-boot-starter-test,如果需要繼續兼容junit4需要自行引入vintage
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
junit5:https://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations
JUnit5常用注解:
@Test :表示方法是測試方法。但是與JUnit4的@Test不同,他的職責非常單一不能聲明任何屬性,拓展的測試將會由Jupiter提供額外測試
@ParameterizedTest :表示方法是參數化測試,下方會有詳細介紹
@RepeatedTest :表示方法可重復執行,下方會有詳細介紹
@DisplayName :為測試類或者測試方法設置展示名稱
@BeforeEach :表示在每個單元測試之前執行
@AfterEach :表示在每個單元測試之后執行
@BeforeAll :表示在所有單元測試之前執行
@AfterAll :表示在所有單元測試之后執行
@Tag :表示單元測試類別,類似於JUnit4中的@Categories
@Disabled :表示測試類或測試方法不執行,類似於JUnit4中的@Ignore
@Timeout :表示測試方法運行如果超過了指定時間將會返回錯誤
@ExtendWith :為測試類或測試方法提供擴展類引用
演示@DisplayName:
@Test
@DisplayName("test1方法")
public void test1(){
System.out.println("test1");
}
演示@BeforeEach和@AfterEach
@BeforeEach
void befor(){
System.out.println("before");
}
@AfterEach
void after(){
System.out.println("after");
}
演示@BeforeAll和@AfterAll
@DisplayName("JUnit5Test測試類")
public class JUnit5Test {
@BeforeEach
void befor(){
System.out.println("before");
}
@Test
@DisplayName("test1方法")
public void test1(){
System.out.println("test1");
}
@Test
@DisplayName("test2方法")
public void test2(){
System.out.println("test2");
}
@AfterEach
void after(){
System.out.println("after");
}
@AfterAll
static void afterAll(){
System.out.println("afterAll");
}
@BeforeAll
static void beforeAll(){
System.out.println("beforeAll");
}
}
運行這個類:

演示@Disabled
在test2方法上加上@Disabled注解,然后執行整個測試類

演示:@Timeout
@Test
@Timeout(value = 3)//默認單位為秒
@DisplayName("測試超時")
void testTime() throws InterruptedException {
TimeUnit.SECONDS.sleep(5);
}

演示:@RepeatedTest
@Test
@RepeatedTest(3)
@DisplayName("test1方法")
public void test1(){
System.out.println("test1");
}