JUnit5是什麼 官網介紹如下 : JUnit 5 is the next generation of JUnit. The goal is to create an up-to-date foundation for developer-side testing on the JVM. This includes focusing on Java 8 and above, as well as enabling many different styles of testing. JUnit 5 is the result of JUnit Lambda and its crowdfunding campaign on Indiegogo.
主要就是說Junit5基於Java8及以上,實現時用到了許多Java8的特性比如Lambda運算式和介面預設方法等
JUnit5分為以下三個模組 1. JUnit Platform JUnit platform的職責 載入測試架構到JVM 定義了 TestEngine API 來對測試架構進行擴充 提供了 Console Launcher來支援命令列和 Maven以及Gradle的外掛程式
關鍵類 : TestEngine、Launcher 2. JUnit Jupiter 提供了JUnit5的編程模型和擴充模型 提供了一個TestEngine的實現(JupiterTestEngine)來跑基於Jupiter的測試
3.Junit Vintage 用來跑JUnit低版本的測試案例,保證向下相容
JUnit5的annotation JUnit5所有的annotation都放在org.junit.jupiter.api包下
1.和JUnit4等價的註解 @Disabled == @Ignore @BeforeEach == @Before 、 @AfterEach == @After
@BeforeAll == @BeforeClass、 @AfterAll == @AfterClass
2. JUnit5新增的註解 1. @DisplayName : 設定測試類別或測試方法的展示內容,在最終結果列印出來時可以看到,內容可以是文本甚至是emoji
@Test @DisplayName("╯°□°)╯") void testWithDisplayNameContainingEmoji() { }
2. @TestInstance : 定義在類上面,用於控制測試類別的執行個體是否是單例的,即該執行個體是否被該類的所有測試方法共用,即PER_CLASS和PER_METHOD兩種模式,定義如下
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented @API(status = STABLE, since = "5.0") public @interface TestInstance
3. @ExtendWith:對測試類別進行擴充,基於java SPI機制,介面為Extension,作為@Runwith的替代,典型的實現有SpringExtension、MockitoExtension
4. @ParameterizedTest:參數化測試,表示測試方法可以帶有參數了
@ParameterizedTest @ValueSource(strings = { "Hello", "World" }) void testWithStringParameter(String argument) { assertNotNull(argument); }
5. @Tag:給類或者方法打標籤,用於進行過濾,類似JUnit4中Categories的概念,可以新定義annotation來達到複製@Tag的效果
@Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Tag("fast") public @interface Fast { }