雖然JUnit5 的測試版本早就出來了,但正式版直到幾年9月份推出,目前最新版5.0.1。幾乎所有的Java 開發人員都會使用JUnit 來做測試,但其實很多自動化測試人員也會使用Junit 。目前,Android單元測試默認使用 Junit4,相信不久的將來也會使用 JUnit5 。
但是介紹 JUnit5 安裝與使用資料並不算太多。本文普及一下JUnit5 安裝與基本使用。
什么是Junit5 ?
先看來個公式:
JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage
這看上去比Junit4 復雜,實際上在導入包時也會復雜一些。
JUnit Platform是在JVM上啟動測試框架的基礎。
JUnit Jupiter是JUnit5擴展的新的編程模型和擴展模型,用來編寫測試用例。Jupiter子項目為在平台上運行Jupiter的測試提供了一個TestEngine (測試引擎)。
JUnit Vintage提供了一個在平台上運行JUnit 3和JUnit 4的TestEngine 。
環境:
IDE:IntelliJ IDEA
版本工具:Maven
如果你從沒使用過IntelliJ IDEA 和Maven的話,那么本文不適合你。
接下來在 IntelliJ IDEA中創建一個Maven項目,創建項目目錄結果如下:
在 pom.xml 文件中添加JUnit5的相關庫。
<dependencies> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-launcher</artifactId> <version>1.0.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.0.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> <version>4.12.1</version> <scope>test</scope> </dependency> </dependencies>
在test.java目錄下創建一個 FistJUnit5Tests 類。代碼如下:
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class FirstJUnit5Tests { @Test void myFirstTest() { assertEquals(2, 1 + 1); } }
明顯看出和Junit4 還是有些不同的。首先,導入測試測試注解(@Test)和斷言方法(assertEquals)的路徑不同。其次,不需要手動把測試和測試方法聲明為 public 了。
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertAll; import org.junit.jupiter.api.*; class FirstJUnit5Tests { @BeforeEach @DisplayName("每條用例開始時執行") void start(){ } @AfterEach @DisplayName("每條用例結束時執行") void end(){ } @Test void myFirstTest() { assertEquals(2, 1 + 1); } @Test @DisplayName("描述測試用例╯°□°)╯") void testWithDisplayName() { } @Test @Disabled("這條用例暫時跑不過,忽略!") void myFailTest(){ assertEquals(1,2); } @Test @DisplayName("運行一組斷言") public void assertAllCase() { assertAll("groupAssert", () -> assertEquals(2, 1 + 1), () -> assertTrue(1 > 0) ); } @Test @DisplayName("依賴注入1") public void testInfo(final TestInfo testInfo) { System.out.println(testInfo.getDisplayName()); } @Test @DisplayName("依賴注入2") public void testReporter(final TestReporter testReporter) { testReporter.publishEntry("name", "Alex"); } }
上面一段代碼,大概展示了Junit5的一些新的特性或與舊版本的不同。我通過用例描述,已經做了介紹。在IDEA中的運行結果如下。
參考:http://junit.org/junit5/docs/current/user-guide/