You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Maven集成测试在编译/测试失败时返回错误码

问题描述

我使用以下bash命令运行集成测试:

mvn clean test-compile failsafe:integration-test -s ./settings.xml

执行后得到输出:

[INFO] 
[INFO] Results:
[INFO] 
[ERROR] Errors: 
[ERROR]   MyJavaIntegrationTestClass » UnsatisfiedDependency Error creating bean with name 'com.xxx...
[INFO] 
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  39.037 s
[INFO] Finished at: 2022-11-08T16:42:26Z
[INFO] ------------------------------------------------------------------------

问题在于代码未完成编译且存在1个测试错误,但构建仍提示成功,命令返回码为0,无法通过返回码判断测试状态。我需要实现:若存在编译或测试运行失败则脚本终止,无异常则脚本通过。

解决方案

方法1:添加failsafe:verify目标

Maven Failsafe插件的integration-test目标仅负责运行测试,不会验证测试结果,因此即使测试失败也会返回成功。添加verify目标后,Maven会检查测试结果,一旦发现错误就会让构建失败并返回非0码。修改后的命令如下:

mvn clean test-compile failsafe:integration-test failsafe:verify -s ./settings.xml

方法2:配置Failsafe插件强制失败

在项目的pom.xml中配置Failsafe插件,开启failOnError参数,让插件在测试出错时直接终止构建。配置示例:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>你的插件版本</version> <!-- 例如3.0.0-M7 -->
            <configuration>
                <failOnError>true</failOnError> <!-- 测试出错时触发构建失败 -->
                <failIfNoTests>false</failIfNoTests> <!-- 可选,无测试时不报错 -->
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>integration-test</goal>
                        <goal>verify</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

配置完成后,直接运行mvn clean verify -s ./settings.xml即可实现需求。

方法3:在bash脚本中检查输出

如果无法修改Maven配置或命令,可以在bash脚本中捕获命令输出,通过关键词检测是否存在错误,示例脚本如下:

#!/bin/bash

# 执行Maven命令并保存输出
mvn_output=$(mvn clean test-compile failsafe:integration-test -s ./settings.xml)
exit_code=$?

# 打印命令输出
echo "$mvn_output"

# 检测是否存在测试错误或编译失败
if echo "$mvn_output" | grep -q "\[ERROR\] Errors:" || echo "$mvn_output" | grep -q "compilation failed"; then
    echo "检测到测试错误或编译失败,脚本终止"
    exit 1
fi

# 检查Maven命令原始退出码
if [ $exit_code -ne 0 ]; then
    echo "Maven命令执行异常,脚本终止"
    exit 1
fi

echo "构建和测试无异常,脚本通过"
exit 0

内容的提问来源于stack exchange,提问作者Sachin Kainth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 22:01:19