在Java 8之前的项目中使用JUnit 5
這篇文章演示了如何在Java 8之前的項目中使用JUnit 5,并解釋了為什么它是一個好主意。
JUnit 5至少需要Java 8作為運行時環境,因此您想將整個項目更新為Java8。但是有時由于某些原因,您無法立即將項目更新為Java8。例如,應用程序服務器的版本生產環境中的產品僅支持Java7。但是由于生產代碼中的某些問題,更新不會很快進行。
現在,問題是如何在不將生產代碼更新為Java 8的情況下使用JUnit 5?
在Maven中(當然也可以在Gradle中),您可以分別為生產代碼和測試代碼設置Java版本。
<build><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><configuration><source>7</source><target>7</target><testSource>8</testSource><testTarget>8</testTarget></configuration></plugin></plugins> </build>前提條件是您使用Java 8 JDK進行構建。
如果嘗試在Java 7生產代碼中使用Java 8功能,則Maven將使構建失敗。
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.0:compile (default-compile) on project junit5-in-pre-java8-projects: Compilation failure [ERROR] /home/sparsick/dev/workspace/junit5-example/junit5-in-pre-java8-projects/src/main/java/Java7Class.java:[8,58] lambda expressions are not supported in -source 7 [ERROR] (use -source 8 or higher to enable lambda expressions)現在,您可以在項目中引入JUnit 5,并開始使用JUnit 5編寫測試。
<dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId><scope>test</scope> </dependency> <dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-engine</artifactId><scope>test</scope> </dependency> <dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-params</artifactId><scope>test</scope> </dependency> <!-- junit-vintage-engine is needed for running elder JUnit4 test with JUnit5--> <dependency><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId><scope>test</scope> </dependency>您不需要遷移舊的JUnit 4測試,因為JUnit 5具有測試引擎,可以與JUnit 5一起運行JUnit 4測試。因此,對于新測試,請使用JUnit 5,并且僅在必須觸摸時才遷移JUnit 4測試。
盡管您無法將生產代碼更新為較新的Java版本,但將測試代碼更新為較新的Java版本有一些好處。
最大的好處是您可以在日常工作中編寫測試時開始學習新的語言功能。 您不會在生產代碼中犯初學者的錯誤。 您可以使用有助于改善測試的新工具。 例如,在JUnit 5中編寫參數化測試比在JUnit 4中編寫更舒適。以我的經驗,在參數化測試有意義的情況下,開發人員使用JUnit 5編寫參數化測試比使用JUnit 4編寫。
上述技術也適用于其他Java版本。 例如,您的生產代碼在Java 11上,而您想在測試代碼中使用Java 12功能。 該技術的另一個用例是在日常工作中學習另一種JVM語言,例如Groovy,Kotlin或Clojure。 然后在測試代碼中使用新語言。
這種方法有一個小陷阱。 IntelliJ IDEA無法分別設置Java版本以進行生產和測試。 因此,您必須將整個項目設置為Java8。如果您的生產代碼使用正確的Java版本,則只有Maven構建會為您提供反饋。
鏈接
- Maven項目設置
翻譯自: https://www.javacodegeeks.com/2019/01/using-junit-5-pre-java-8-projects.html
總結
以上是生活随笔為你收集整理的在Java 8之前的项目中使用JUnit 5的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ps下一个图层快捷键(ps下一个图层快捷
- 下一篇: 绿色征途任务快捷键(绿色征途怎么加点)