如何在使用构建和部署时运行 Spring Boot 应用程序的单元测试spring boot:run
命令。
我的期望是在运行应用程序之前执行所有单元测试,但我不想创建另一个 Maven 命令,例如mvn test
before.
我的问题:
我制作了一个简单的 Spring Boot 应用程序,我可以找到一种在从 intellij 或命令行运行应用程序时运行单元测试的方法。首先,我认为可能是我的配置错误或测试类名称错误或者项目结构错误。所以我从 intellij 模板创建了 spring boot 应用程序。令我高兴的是,它已经编写了默认测试,因此我只需运行应用程序即可。不幸的是测试没有执行。
这是intellij创建的项目结构、pom.xml、主类和单元测试的屏幕截图。项目由 intetelij 创建 https://i.stack.imgur.com/5J8OW.png
我更改了测试运行程序并测试失败并再次尝试。相同的结果。单元测试改为失败 https://i.stack.imgur.com/b7vpg.png
我用谷歌搜索了下面隐藏的内容spring boot:run
命令在这里http://docs.spring.io/spring-boot/docs/current/maven-plugin/run-mojo.html http://docs.spring.io/spring-boot/docs/current/maven-plugin/run-mojo.html
我在手册顶部发现了一些有趣的内容:“在执行自身之前调用生命周期阶段测试编译的执行。”所以我的理解是这个命令只编译测试但不运行它们?如果是这样,问题是 - 是否可以通过向命令添加一些标志来添加“测试”阶段?
您的问题与 Maven 生命周期有关。根据docs http://docs.spring.io/spring-boot/docs/current/maven-plugin/run-mojo.html为了spring-boot:run
,它绑定到生命周期阶段validate
默认情况下,并调用阶段test-compile
在执行之前。
你要求的是execute运行应用程序之前进行测试。您可以使用 POM 中的自定义 Maven 配置文件来完成此操作 - 如下所示。
<project>
<profiles>
<profile>
<id>test-then-run</id>
<build>
<defaultGoal>verify</defaultGoal>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<id>spring-boot-run</id>
<phase>verify</phase>
<goals>
<goal>run</goal>
</goals>
<inherited>false</inherited>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
...
</profiles>
...
</project>
将其添加到 POM 中后,您就可以运行测试并使用以下命令启动应用程序:
mvn -P test-then-run
这绑定了run
目标为verify
相而不是validate
阶段,这意味着测试将首先运行。您可以在此处查看各个阶段的运行顺序:https://maven.apache.org/ref/3.3.9/maven-core/lifecycles.html https://maven.apache.org/ref/3.3.9/maven-core/lifecycles.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)