unity-test-runner
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseUnity Test Runner
Unity 测试运行器
Overview
概述
This skill enables automated execution and analysis of Unity Test Framework tests directly from the command line. It handles the complete test workflow: detecting Unity Editor installations across platforms (Windows/macOS/Linux), configuring test parameters, executing tests in EditMode or PlayMode, parsing NUnit XML results, and generating detailed failure reports with actionable insights.
该技能支持直接从命令行自动执行和分析Unity Test Framework测试。它处理完整的测试工作流:跨平台(Windows/macOS/Linux)检测Unity Editor安装、配置测试参数、在EditMode或PlayMode下执行测试、解析NUnit XML结果,并生成带有可行洞察的详细失败报告。
When to Use This Skill
适用场景
Use this skill when:
- Executing Unity Test Framework tests from command line
- Running PlayMode or EditMode tests for game logic validation
- Analyzing test failures and generating failure reports
- Integrating Unity tests into CI/CD pipelines
- Debugging test failures with detailed stack traces and file locations
- Validating Unity project changes before commits
Example user requests:
- "Run all Unity tests in my project"
- "Execute PlayMode tests and show me the results"
- "Run tests in the Combat category"
- "Check if my Unity tests are passing"
- "Run EditMode tests only"
在以下场景使用该技能:
- 从命令行执行Unity Test Framework测试
- 运行PlayMode或EditMode测试以验证游戏逻辑
- 分析测试失败并生成失败报告
- 将Unity测试集成到CI/CD流水线
- 通过详细堆栈跟踪和文件位置调试测试失败
- 提交前验证Unity项目变更
用户请求示例:
- "运行我项目中的所有Unity测试"
- "执行PlayMode测试并展示结果"
- "运行Combat分类下的测试"
- "检查我的Unity测试是否通过"
- "仅运行EditMode测试"
Workflow
工作流
Follow this workflow when the skill is invoked:
调用该技能时遵循以下工作流:
1. Detect Unity Editor Installation
1. 检测Unity Editor安装
Use the script to automatically locate the Unity Editor:
find-unity-editor.jsbash
node scripts/find-unity-editor.js --jsonScript behavior:
- Scans platform-specific default installation paths
- Detects all installed Unity versions
- Returns the latest version by default
- Can target specific version with flag
--version <version>
Output:
json
{
"found": true,
"editorPath": "C:\\Program Files\\Unity\\Hub\\Editor\\2021.3.15f1\\Editor\\Unity.exe",
"version": "2021.3.15f1",
"platform": "win32",
"allVersions": ["2021.3.15f1", "2020.3.30f1"]
}If multiple versions are found:
- Present all available versions to the user
- Ask user to confirm which version to use
- Or use the latest version by default
If no Unity Editor is found:
- Report error with searched paths
- Ask user to provide Unity Editor path manually
- Store the path for future use
使用脚本自动定位Unity Editor:
find-unity-editor.jsbash
node scripts/find-unity-editor.js --json脚本行为:
- 扫描平台特定的默认安装路径
- 检测所有已安装的Unity版本
- 默认返回最新版本
- 可通过参数指定目标版本
--version <version>
输出:
json
{
"found": true,
"editorPath": "C:\\Program Files\\Unity\\Hub\\Editor\\2021.3.15f1\\Editor\\Unity.exe",
"version": "2021.3.15f1",
"platform": "win32",
"allVersions": ["2021.3.15f1", "2020.3.30f1"]
}如果找到多个版本:
- 向用户展示所有可用版本
- 询问用户确认使用哪个版本
- 或默认使用最新版本
如果未找到Unity Editor:
- 报告包含已搜索路径的错误
- 询问用户手动提供Unity Editor路径
- 存储该路径以备后续使用
2. Verify Unity Project Path
2. 验证Unity项目路径
Confirm the current directory contains a valid Unity project using cross-platform checks:
typescript
// Use Read tool to check for Unity project indicators
Read({ file_path: "ProjectSettings/ProjectVersion.txt" })
// Use Glob to verify Assets directory exists
Glob({ pattern: "Assets/*", path: "." })Validation steps:
- Verify directory exists
Assets/ - Verify exists
ProjectSettings/ProjectVersion.txt - Read to get Unity version
ProjectVersion.txt - Warn if Editor version doesn't match project version
Example ProjectVersion.txt:
m_EditorVersion: 2021.3.15f1
m_EditorVersionWithRevision: 2021.3.15f1 (e8e88743f9e5)通过跨平台检查确认当前目录包含有效的Unity项目:
typescript
// 使用Read工具检查Unity项目标识
Read({ file_path: "ProjectSettings/ProjectVersion.txt" })
// 使用Glob工具验证Assets目录存在
Glob({ pattern: "Assets/*", path: "." })验证步骤:
- 验证目录存在
Assets/ - 验证存在
ProjectSettings/ProjectVersion.txt - 读取获取Unity版本
ProjectVersion.txt - 如果Editor版本与项目版本不匹配则发出警告
ProjectVersion.txt示例:
m_EditorVersion: 2021.3.15f1
m_EditorVersionWithRevision: 2021.3.15f1 (e8e88743f9e5)3. Configure Test Settings
3. 配置测试设置
Determine test execution parameters. Use tool if parameters are not specified:
AskUserQuestionRequired settings:
- Test Mode: EditMode, PlayMode, or Both
- Test Platform: EditMode tests use "EditMode", PlayMode can specify platform (e.g., "StandaloneWindows64", "Android", "iOS")
Optional settings:
- Test Categories: Semicolon-separated list (e.g., "Combat;AI;Physics")
- Test Filter: Regex pattern or semicolon-separated test names
- Results Output Path: Default to in project root
TestResults.xml
Configuration example:
typescript
AskUserQuestion({
questions: [{
question: "Which test mode should be executed?",
header: "Test Mode",
multiSelect: false,
options: [
{ label: "EditMode Only", description: "Fast unit tests without Play Mode" },
{ label: "PlayMode Only", description: "Full Unity engine tests" },
{ label: "Both Modes", description: "Run all tests (slower)" }
]
}]
})确定测试执行参数。如果参数未指定,使用工具询问:
AskUserQuestion必填设置:
- 测试模式:EditMode、PlayMode或两者都选
- 测试平台:EditMode测试使用"EditMode",PlayMode可指定平台(例如"StandaloneWindows64"、"Android"、"iOS")
可选设置:
- 测试分类:分号分隔的列表(例如"Combat;AI;Physics")
- 测试过滤器:正则表达式模式或分号分隔的测试名称
- 结果输出路径:默认输出到项目根目录的
TestResults.xml
配置示例:
typescript
AskUserQuestion({
questions: [{
question: "应执行哪种测试模式?",
header: "测试模式",
multiSelect: false,
options: [
{ label: "仅EditMode", description: "无需Play Mode的快速单元测试" },
{ label: "仅PlayMode", description: "完整Unity引擎测试" },
{ label: "两种模式", description: "运行所有测试(速度较慢)" }
]
}]
})4. Execute Tests via Command Line
4. 通过命令行执行测试
Build and execute the Unity command line test command:
Command structure:
bash
<UnityEditorPath> -runTests -batchmode -projectPath <ProjectPath> \
-testPlatform <EditMode|PlayMode> \
-testResults <OutputPath> \
[-testCategory <Categories>] \
[-testFilter <Filter>] \
-logFile -Example commands:
EditMode tests:
bash
"C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Unity.exe" \
-runTests -batchmode \
-projectPath "D:\Projects\MyGame" \
-testPlatform EditMode \
-testResults "TestResults-EditMode.xml" \
-logFile -PlayMode tests with category filter:
bash
"C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Unity.exe" \
-runTests -batchmode \
-projectPath "D:\Projects\MyGame" \
-testPlatform PlayMode \
-testResults "TestResults-PlayMode.xml" \
-testCategory "Combat;AI" \
-logFile -Execution notes:
- Use tool with
Bashfor long-running testsrun_in_background: true - Set timeout appropriately (default: 5-10 minutes, adjust based on test count)
- Monitor output for progress indicators
- Capture both stdout and stderr
Example execution:
typescript
Bash({
command: `"${unityPath}" -runTests -batchmode -projectPath "${projectPath}" -testPlatform EditMode -testResults "TestResults.xml" -logFile -`,
description: "Execute Unity EditMode tests",
timeout: 300000, // 5 minutes
run_in_background: true
})构建并执行Unity命令行测试命令:
命令结构:
bash
<UnityEditorPath> -runTests -batchmode -projectPath <ProjectPath> \
-testPlatform <EditMode|PlayMode> \
-testResults <OutputPath> \
[-testCategory <Categories>] \
[-testFilter <Filter>] \
-logFile -命令示例:
EditMode测试:
bash
"C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Unity.exe" \
-runTests -batchmode \
-projectPath "D:\Projects\MyGame" \
-testPlatform EditMode \
-testResults "TestResults-EditMode.xml" \
-logFile -带分类过滤的PlayMode测试:
bash
"C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Unity.exe" \
-runTests -batchmode \
-projectPath "D:\Projects\MyGame" \
-testPlatform PlayMode \
-testResults "TestResults-PlayMode.xml" \
-testCategory "Combat;AI" \
-logFile -执行注意事项:
- 对长时间运行的测试,使用工具并设置
Bashrun_in_background: true - 适当设置超时时间(默认:5-10分钟,根据测试数量调整)
- 监控输出中的进度指标
- 同时捕获stdout和stderr
执行示例:
typescript
Bash({
command: `"${unityPath}" -runTests -batchmode -projectPath "${projectPath}" -testPlatform EditMode -testResults "TestResults.xml" -logFile -`,
description: "执行Unity EditMode测试",
timeout: 300000, // 5分钟
run_in_background: true
})5. Parse Test Results
5. 解析测试结果
After tests complete, parse the NUnit XML results using :
parse-test-results.jsbash
node scripts/parse-test-results.js TestResults.xml --jsonScript output:
json
{
"summary": {
"total": 10,
"passed": 7,
"failed": 2,
"skipped": 1,
"duration": 12.345
},
"failures": [
{
"name": "TestPlayerTakeDamage",
"fullName": "Tests.Combat.PlayerTests.TestPlayerTakeDamage",
"message": "Expected: 90\n But was: 100",
"stackTrace": "at Tests.Combat.PlayerTests.TestPlayerTakeDamage () [0x00001] in Assets/Tests/Combat/PlayerTests.cs:42",
"file": "Assets/Tests/Combat/PlayerTests.cs",
"line": 42
}
],
"allTests": [...]
}Result analysis:
- Extract test summary statistics
- Identify all failed tests
- Extract file paths and line numbers from stack traces
- Categorize failures by type (assertion, exception, timeout)
测试完成后,使用解析NUnit XML结果:
parse-test-results.jsbash
node scripts/parse-test-results.js TestResults.xml --json脚本输出:
json
{
"summary": {
"total": 10,
"passed": 7,
"failed": 2,
"skipped": 1,
"duration": 12.345
},
"failures": [
{
"name": "TestPlayerTakeDamage",
"fullName": "Tests.Combat.PlayerTests.TestPlayerTakeDamage",
"message": "Expected: 90\n But was: 100",
"stackTrace": "at Tests.Combat.PlayerTests.TestPlayerTakeDamage () [0x00001] in Assets/Tests/Combat/PlayerTests.cs:42",
"file": "Assets/Tests/Combat/PlayerTests.cs",
"line": 42
}
],
"allTests": [...]
}结果分析:
- 提取测试汇总统计数据
- 识别所有失败的测试
- 从堆栈跟踪中提取文件路径和行号
- 按类型对失败进行分类(断言失败、异常、超时)
6. Analyze Test Failures
6. 分析测试失败
For each failed test, analyze the failure using :
references/test-patterns.jsonAnalysis steps:
- Load test patterns database:
typescript
Read({ file_path: "references/test-patterns.json" })-
Match failure message against patterns:
- Assertion failures:
Expected: <X> But was: <Y> - Null reference failures:
Expected: not null But was: <null> - Timeout failures:
TimeoutException|Test exceeded time limit - Threading errors:
Can't be called from.*main thread - Object lifetime issues:
has been destroyed|MissingReferenceException
- Assertion failures:
-
Determine failure category:
- ValueMismatch: Incorrect assertion value
- NullValue: Unexpected null reference
- Performance: Timeout or slow execution
- TestSetup: Setup/TearDown failure
- ObjectLifetime: Destroyed object access
- Threading: Wrong thread execution
-
Generate fix suggestions:
- Load common solutions from test-patterns.json
- Match solutions to failure pattern
- Provide concrete code examples
Example failure analysis:
markdown
**Test**: Tests.Combat.PlayerTests.TestPlayerTakeDamage
**Location**: Assets/Tests/Combat/PlayerTests.cs:42
**Result**: FAILED
**Failure Message**:
Expected: 90
But was: 100
**Analysis**:
- Category: ValueMismatch (Assertion Failure)
- Pattern: Expected/actual value mismatch
- Root Cause: Player health not decreasing after TakeDamage() call
**Possible Causes**:
1. TakeDamage() method not implemented correctly
2. Player health not initialized properly
3. Damage value passed incorrectly
**Suggested Solutions**:
1. Verify TakeDamage() implementation:
```csharp
public void TakeDamage(int damage) {
health -= damage; // Ensure this line exists
}-
Check test setup:csharp
[SetUp] public void SetUp() { player = new Player(); player.Health = 100; // Ensure proper initialization } -
Verify test assertion:csharp
player.TakeDamage(10); Assert.AreEqual(90, player.Health); // Expected: 90
undefined对于每个失败的测试,使用分析失败原因:
references/test-patterns.json分析步骤:
- 加载测试模式数据库:
typescript
Read({ file_path: "references/test-patterns.json" })-
将失败消息与模式匹配:
- 断言失败:
Expected: <X> But was: <Y> - 空引用失败:
Expected: not null But was: <null> - 超时失败:
TimeoutException|Test exceeded time limit - 线程错误:
Can't be called from.*main thread - 对象生命周期问题:
has been destroyed|MissingReferenceException
- 断言失败:
-
确定失败类别:
- ValueMismatch:断言值不正确
- NullValue:意外的空引用
- Performance:超时或执行缓慢
- TestSetup:Setup/TearDown失败
- ObjectLifetime:已销毁对象访问
- Threading:错误线程执行
-
生成修复建议:
- 从test-patterns.json加载常见解决方案
- 将解决方案与失败模式匹配
- 提供具体代码示例
失败分析示例:
markdown
**测试**: Tests.Combat.PlayerTests.TestPlayerTakeDamage
**位置**: Assets/Tests/Combat/PlayerTests.cs:42
**结果**: 失败
**失败消息**:
Expected: 90
But was: 100
**分析**:
- 类别: ValueMismatch(断言失败)
- 模式: 预期值与实际值不匹配
- 根本原因: 调用TakeDamage()后玩家生命值未减少
**可能原因**:
1. TakeDamage()方法未正确实现
2. 玩家生命值未正确初始化
3. 传入的伤害值不正确
**建议解决方案**:
1. 验证TakeDamage()实现:
```csharp
public void TakeDamage(int damage) {
health -= damage; // 确保该行存在
}-
检查测试设置:csharp
[SetUp] public void SetUp() { player = new Player(); player.Health = 100; // 确保正确初始化 } -
验证测试断言:csharp
player.TakeDamage(10); Assert.AreEqual(90, player.Health); // 预期值:90
undefined7. Generate Test Report
7. 生成测试报告
Create a comprehensive test report for the user:
Report structure:
markdown
undefined为用户创建全面的测试报告:
报告结构:
markdown
undefinedUnity Test Results
Unity 测试结果
Summary
汇总
- Total Tests: 10
- ✓ Passed: 7 (70%)
- ✗ Failed: 2 (20%)
- ⊘ Skipped: 1 (10%)
- Duration: 12.35s
- 总测试数: 10
- ✓ 通过: 7 (70%)
- ✗ 失败: 2 (20%)
- ⊘ 跳过: 1 (10%)
- 耗时: 12.35秒
Test Breakdown
测试细分
- EditMode Tests: 5 passed, 1 failed
- PlayMode Tests: 2 passed, 1 failed
- EditMode测试: 5通过,1失败
- PlayMode测试: 2通过,1失败
Failed Tests
失败测试
1. Tests.Combat.PlayerTests.TestPlayerTakeDamage
1. Tests.Combat.PlayerTests.TestPlayerTakeDamage
Location: Assets/Tests/Combat/PlayerTests.cs:42
Failure: Expected: 90, But was: 100
Analysis: Player health not decreasing after TakeDamage() call.
Suggested Fix: Verify TakeDamage() implementation decreases health correctly.
位置: Assets/Tests/Combat/PlayerTests.cs:42
失败原因: 预期值:90,实际值:100
分析: 调用TakeDamage()后玩家生命值未减少。
建议修复: 验证TakeDamage()实现是否正确减少生命值。
2. Tests.AI.EnemyTests.TestEnemyChasePlayer
2. Tests.AI.EnemyTests.TestEnemyChasePlayer
Location: Assets/Tests/AI/EnemyTests.cs:67
Failure: TimeoutException - Test exceeded time limit (5s)
Analysis: Infinite loop or missing yield in coroutine test.
Suggested Fix: Add attribute and use in test loop.
[UnityTest]yield return null位置: Assets/Tests/AI/EnemyTests.cs:67
失败原因: TimeoutException - 测试超出时间限制(5秒)
分析: 协程测试中存在无限循环或缺少yield。
建议修复: 添加属性并在测试循环中使用。
[UnityTest]yield return nullNext Steps
后续步骤
- Review failed test locations and fix implementation
- Re-run tests after fixes by re-invoking the skill
- Consider adding more assertions for edge cases
**Report delivery:**
- Present report in formatted Markdown
- Highlight critical failures
- Provide file:line references for quick navigation
- Offer to help fix specific failures if user requests- 查看失败测试的位置并修复实现
- 修复后重新调用该技能以重新运行测试
- 考虑为边缘情况添加更多断言
**报告交付:**
- 以格式化的Markdown展示报告
- 突出显示严重失败
- 提供文件:行号引用以便快速导航
- 如果用户请求,提供帮助修复特定失败的服务Best Practices
最佳实践
When using this skill:
-
Run EditMode tests first - They're faster and catch basic logic errors
- Reserve PlayMode tests for Unity-specific features
- Use EditMode for pure C# logic and data structures
-
Use test categories - Filter tests for faster iteration
- runs only Combat tests
-testCategory "Combat" - Helpful during active development of specific features
-
Monitor test duration - Set appropriate timeouts
- EditMode: 1-3 minutes typical
- PlayMode: 5-15 minutes typical
- Adjust timeout based on test count
-
Check Unity version compatibility - Ensure Editor matches project version
- Mismatched versions may cause test failures
- Test results may be inconsistent across versions
-
Parse results immediately - Don't wait for manual review
- Automated parsing catches issues faster
- Provides actionable file:line information
-
Analyze failure patterns - Look for common causes
- Similar failures often indicate systemic issues
- Fix root cause instead of individual symptoms
-
Preserve test results - Keep XML files for debugging
- Results contain full stack traces
- Useful for comparing test runs
-
Handle long-running tests - Use background execution
- Monitor progress with tool
BashOutput - Provide status updates to user
- Monitor progress with
使用该技能时:
-
先运行EditMode测试 - 它们速度更快,能捕获基本逻辑错误
- 保留PlayMode测试用于Unity特定功能
- 对纯C#逻辑和数据结构使用EditMode
-
使用测试分类 - 过滤测试以加快迭代速度
- 仅运行Combat分类的测试
-testCategory "Combat" - 在特定功能的活跃开发阶段非常有用
-
监控测试耗时 - 设置适当的超时时间
- EditMode:通常1-3分钟
- PlayMode:通常5-15分钟
- 根据测试数量调整超时时间
-
检查Unity版本兼容性 - 确保Editor版本与项目版本匹配
- 版本不匹配可能导致测试失败
- 不同版本的测试结果可能不一致
-
立即解析结果 - 不要等待手动审查
- 自动解析能更快发现问题
- 提供可行的文件:行号信息
-
分析失败模式 - 寻找常见原因
- 类似失败通常表明系统性问题
- 修复根本原因而非个别症状
-
保留测试结果 - 保留XML文件用于调试
- 结果包含完整堆栈跟踪
- 有助于比较不同测试运行的结果
-
处理长时间运行的测试 - 使用后台执行
- 使用工具监控进度
BashOutput - 向用户提供状态更新
- 使用
Resources
资源
scripts/find-unity-editor.js
scripts/find-unity-editor.js
Cross-platform Unity Editor path detection script. Automatically scans default installation directories for Windows, macOS, and Linux, detects all installed Unity versions, and returns the latest version or a specific requested version.
Usage:
bash
undefined跨平台Unity Editor路径检测脚本。自动扫描Windows、macOS和Linux的默认安装目录,检测所有已安装的Unity版本,并返回最新版本或指定的目标版本。
用法:
bash
undefinedFind latest Unity version
查找最新Unity版本
node scripts/find-unity-editor.js --json
node scripts/find-unity-editor.js --json
Find specific version
查找特定版本
node scripts/find-unity-editor.js --version 2021.3.15f1 --json
**Output**: JSON with Unity Editor path, version, platform, and all available versions.node scripts/find-unity-editor.js --version 2021.3.15f1 --json
**输出**:包含Unity Editor路径、版本、平台和所有可用版本的JSON。scripts/parse-test-results.js
scripts/parse-test-results.js
NUnit XML results parser for Unity Test Framework output. Extracts test statistics, failure details, stack traces, and file locations from XML results.
Usage:
bash
undefined用于解析Unity Test Framework输出的NUnit XML结果解析器。从XML结果中提取测试统计数据、失败详情、堆栈跟踪和文件位置。
用法:
bash
undefinedParse test results with JSON output
解析测试结果并输出JSON
node scripts/parse-test-results.js TestResults.xml --json
node scripts/parse-test-results.js TestResults.xml --json
Parse with formatted console output
解析并输出格式化的控制台内容
node scripts/parse-test-results.js TestResults.xml
**Output**: JSON with test summary, failure details including file paths and line numbers, and full test list.node scripts/parse-test-results.js TestResults.xml
**输出**:包含测试汇总、失败详情(包括文件路径和行号)以及完整测试列表的JSON。references/test-patterns.json
references/test-patterns.json
Comprehensive database of Unity testing patterns, NUnit assertions, common failure patterns, and best practices. Includes:
- NUnit assertion reference (equality, collections, exceptions, Unity-specific)
- Common failure patterns with regex matching
- Failure categories and root cause analysis
- Solution templates with code examples
- EditMode vs PlayMode guidance
- Unity-specific testing patterns (coroutines, scenes, prefabs, physics)
- Testing best practices
Usage: Load this file when analyzing test failures to match failure messages against patterns and generate fix suggestions.
Unity测试模式、NUnit断言、常见失败模式和最佳实践的综合数据库。包括:
- NUnit断言参考(相等性、集合、异常、Unity特定)
- 带正则匹配的常见失败模式
- 失败类别和根本原因分析
- 带代码示例的解决方案模板
- EditMode与PlayMode测试指南
- Unity特定测试模式(协程、场景、预制件、物理)
- 测试最佳实践
用法:分析测试失败时加载此文件,将失败消息与模式匹配并生成修复建议。