小编典典

Spring Boot不运行单元测试

spring-boot

在使用spring boot:run命令构建和部署时,如何运行Spring Boot应用程序的单元测试。

我的期望是在运行应用程序之前执行我所有的单元测试,但是我不想像以前那样做另一个Maven命令mvn test

我的问题:我做了一个简单的spring
boot应用程序,当我从intellij或命令行运行应用程序时,我找不到运行单元测试的方法。首先,我认为也许我配置错误或测试类的名称错误或项目结构错误。所以我从intellij模板创建了spring
boot应用程序。令我高兴的是,它已经编写了默认测试,所以我只运行应用程序。很遗憾,未执行测试。

这是intellij创建的项目结构,pom.xml,主类和单元测试的屏幕快照。intetelij创建的项目

我更改了测试运行程序并测试失败,然后再次尝试。结果相同。 单元测试更改为失败

我在spring boot:run这里http://docs.spring.io/spring-boot/docs/current/maven-
plugin/run-mojo.html搜索了隐藏在命令 下方的内容

我在手册开头发现了一些有趣的东西:“在执行生命周期阶段测试编译之前先执行它。” 因此,我的理解是该命令仅编译测试而不运行测试?如果是,那么问题是-
是否可以通过在命令中添加一些标志来添加“测试”阶段?


阅读 407

收藏
2020-05-30

共1个答案

小编典典

您的问题是与Maven生命周期有关。根据的文档,默认情况下,spring- boot:run它绑定到lifecyle阶段validate,并test-compile在执行之前调用该阶段。

您要求的是在运行应用程序之前 执行 测试。您可以使用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

2020-05-30