我为Maven创建了一个示例Groovy项目,该项目在一个项目中混合了Spock测试和JUnit 5测试。 在下一节中,我将描述如何设置这种Maven项目。
在项目中启用Groovy
首先,您必须在项目中启用Groovy。 一种可能性是将GMavenPlus插件添加到您的项目中。
< build >
< plugins >
< plugin >
< groupId >org.codehaus.gmavenplus</ groupId >
< artifactId >gmavenplus-plugin</ artifactId >
< version >1.6.2</ version >
< executions >
< execution >
< goals >
< goal >addSources</ goal >
< goal >addTestSources</ goal >
< goal >compile</ goal >
< goal >compileTests</ goal >
</ goals >
</ execution >
</ executions >
</ plugin >
</ plugins > </ build >
目标addSources和addTestSources将Groovy(测试)源添加到Maven的主要(测试)源。 默认位置是src / main / groovy (对于主源)和src / test / groovy (对于测试源)。 目标编译和compileTests编译Groovy(测试)代码。 如果您没有Groovy主代码,则可以省略addSource和compile 。
上面的配置始终使用最新发布的Groovy版本。 如果要确保使用特定的Groovy版本,则必须将特定的Groovy依赖项添加到类路径中。
< dependencies >
< dependency >
< groupId >org.codehaus.groovy</ groupId >
< artifactId >groovy</ artifactId >
< version >2.5.6</ version >
</ dependency >
</ dependencies >
在项目中启用JUnit 5
在项目中使用JUnit 5的最简单设置是在测试类路径中添加JUnit Jupiter依赖关系,并配置正确版本的Maven Surefire插件(至少为2.22.0版)。
< dependencies > <!--... maybe more dependencies -->
< dependency >
< groupId >org.junit.jupiter</ groupId >
< artifactId >junit-jupiter</ artifactId >
< scope >test</ scope >
</ dependency >
</ dependencies >
< dependencyManagement >
< dependencies >
< dependency >
< groupId >org.junit</ groupId >
< artifactId >junit-bom</ artifactId >
< version >${junit.jupiter.version}</ version >
< scope >import</ scope >
< type >pom</ type >
</ dependency >
</ dependencies >
</ dependencyManagement >
< build >
< plugins >
<!-- other plugins -->
< plugin >
< artifactId >maven-surefire-plugin</ artifactId >
< version >2.22.1</ version >
</ plugin >
</ plugins >
</ build >
在项目中启用Spock
选择正确的Spock依赖项取决于您在项目中使用的Groovy版本。 在我们的例子中,是Groovy 2.5版。 因此,我们在测试类路径中需要版本1.x-groovy-2.5的Spock。
< dependencies >
<!-- more dependencies -->
< dependency >
< groupId >org.spockframework</ groupId >
< artifactId >spock-core</ artifactId >
< version >1.3-groovy-2.5</ version >
< scope >test</ scope >
</ dependency >
</ dependencies >
现在期望Spock测试和JUnit5测试在Maven构建中执行。 但是Maven只执行JUnit5测试。 所以发生了什么事?
我开始将Maven Surefire插件版本更改为2.21.0。 然后执行了Spock测试,但没有执行JUnit5测试。 原因是,在Maven Surefire插件的2.22.0版本中,默认情况下,JUnit Platform Provider替换了JUnit4 provider。 但是版本1.x中的Spock基于JUnit4。 这将在Spock版本2中进行更改。此版本将基于JUnit5平台。 因此,对于Spock 1.x,我们必须将JUnit Vintage依赖项添加到测试类路径中。
< dependencies >
<!-- more dependencies -->
< dependency > <!--Only necessary for surefire to run spock tests during the maven build -->
< groupId >org.junit.vintage</ groupId >
< artifactId >junit-vintage-engine</ artifactId >
< scope >test</ scope >
</ dependency >
</ dependencies >
这允许在JUnit平台上运行较早的JUnit(3/4)测试。 使用此配置,Spock和JUnit 5测试都在Maven构建中执行。
链接
- Groovy的示例Maven设置,包括Github上的JUnit 5和Spock
- Maven GMaven Plus插件
- Maven Surefire插件–使用JUnit 5平台
- JUnit 5用户指南
- Spock框架
翻译自: https://www.javacodegeeks.com/2019/03/maven-project-setup-mixing-spock-junit-5-tests.html