这篇文章演示了如何在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