我正在尝试通过 maven 命令分离单元测试和集成测试。
pom.xml
....
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<includes>
<include>**/*Fast*</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
</project>
这是我的集成测试
@RunWith(SpringRunner.class)
@SpringBootTest(classes = StudentApplication.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class StudentControllerIT {
...
这是单元测试
@RunWith(SpringRunner.class)
@WebMvcTest(value = StudentController.class, secure = false)
public class StudentFastControllerTest {
....
现在当我尝试运行命令
mvn test
那么只有StudentFastControllerTest
测试已执行,但是当我运行命令时 mvn integration-test
或 mvn verify
两个测试类都被执行,而不仅仅是 StudentControllerIT
.
最佳答案
编辑:有两种方法对我有用:
1) 使用 maven-failsafe 配置(我得到了来自 this answer 的帮助):
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<executions>
<execution>
<id>it-tests</id>
<phase>none</phase>
<configuration>
<includes>
<include>**/*IT.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
请注意,此执行是 i) 由单词 标识的it-tests 和 ii) 将其相位设置为 无 .后者将这些测试与默认生命周期分离,而前者使我们能够使用以下命令按需运行它们:
mvn failsafe:integration-test@it-tests
让集成测试以
IT
为后缀也很重要。和我们将它们包含在这个 <includes>
中的方式相同我们对 <exclude>
做同样的事情其他插件的部分,例如surefire。2) 使用配置文件
在 简介部分您为集成测试添加配置文件:
<profile>
<id>it-tests</id>
<build>
<plugins>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<configuration>
<includes>
<include>**/*IT.java</include>
</includes>
</configuration>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
此外,将以下内容添加到配置文件配置部分 如果 您在单独的测试源目录中进行了集成测试,在本例中
test-integration
:<testSourceDirectory>test/test-integration/java</testSourceDirectory>
现在回到 插件部分 并在您的
maven-surefire-plugin
上, 从 mvn test
排除集成测试通过将以下内容添加到其配置部分:<excludes>
<exclude>**/*IT.java</exclude>
</excludes>
最后,将以下执行添加到您的 maven-failsafe-plugin:
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
结果(至少在我的情况下),集成测试不会在
mvn test
期间执行。但是当我运行时:mvn failsafe:integration-test -Pit-tests
只有我的集成测试被执行。
我希望这也适用于你。
关于maven - 如何使用maven在spring boot中只执行集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49210541/