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

Unity单元测试失败但GitLab CI Shell执行器流水线任务仍成功

解决Unity测试失败但GitLab CI流水线显示成功的问题

哦,这个坑我太熟了!之前帮好几个做Unity的朋友踩过——核心问题出在GitLab CI默认靠进程退出码判断任务成败,但Unity的测试命令哪怕全挂了,也会返回0(成功)的退出码,完全不管测试结果。下面是一步步的排查和解决方法:

1. 本质原因:Unity测试命令不返回错误码

Unity的批量测试命令(比如Unity.exe -batchmode -runTests ...)有个“特性”:不管测试用例通过还是失败,进程都会返回0的退出码。而GitLab CI只会看这个退出码——只要是0就判定任务成功,完全不会去解析results.xml里的测试结果。

2. 解决方案:手动解析测试结果并返回对应退出码

你需要在Unity测试命令执行完后,加一段脚本逻辑,解析results.xml里的失败计数,然后让脚本返回非0的退出码(比如1)来告诉GitLab CI“测试失败了”。

示例脚本(Windows PowerShell)

# 运行Unity批量测试
& "C:\Program Files\Unity\Hub\Editor\2022.3.10f1\Editor\Unity.exe" `
  -batchmode `
  -runTests `
  -testPlatform editmode `
  -projectPath ".\YourUnityProject" `
  -logFile test.log `
  -resultsFile results.xml

# 解析results.xml,提取失败用例数量
$testResults = [xml](Get-Content results.xml)
$failureCount = $testResults.testRun.results.failureCount

# 根据失败数量返回对应退出码
if ($failureCount -gt 0) {
    Write-Host "❌ 测试失败,共 $failureCount 个用例未通过"
    exit 1
} else {
    Write-Host "✅ 所有测试用例通过"
    exit 0
}

示例脚本(Linux/macOS Bash)

# 运行Unity批量测试
/opt/Unity/Editor/Unity \
  -batchmode \
  -runTests \
  -testPlatform editmode \
  -projectPath "./YourUnityProject" \
  -logFile test.log \
  -resultsFile results.xml

# 用xmllint解析results.xml(需要先安装libxml2-utils)
failureCount=$(xmllint --xpath "string(/testRun/results/@failureCount)" results.xml)

# 判断并返回退出码
if [ "$failureCount" -gt 0 ]; then
    echo "❌ 测试失败,共 $failureCount 个用例未通过"
    exit 1
else
    echo "✅ 所有测试用例通过"
    exit 0
fi

3. 调整gitlab-ci.yml配置

确保你的CI任务调用的是上面的处理脚本,而不是直接调用Unity命令,同时配置artifacts保存日志和结果文件方便排查:

stages:
  - test

unity-test-job:
  stage: test
  script:
    # Windows环境调用PowerShell脚本
    - .\run-unity-tests.ps1
    # Linux/macOS环境调用Bash脚本
    # - chmod +x run-unity-tests.sh && ./run-unity-tests.sh
  artifacts:
    paths:
      - test.log
      - results.xml
    when: always # 不管成功失败都保存日志,方便排查

4. 额外排查点

  • 验证本地脚本的退出码:在本地运行脚本后,Windows下输入echo $LASTEXITCODE,Linux/macOS下输入echo $?,确认测试失败时返回1,成功时返回0。
  • Runner权限问题:如果是Windows Runner,确保GitLab Runner服务是以有权访问Unity和项目文件的用户运行的;Linux/macOS下要给脚本加执行权限(chmod +x)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:36:10