unity-testrunner

Unity Test Framework CLI automation and test writing patterns. Masters batchmode execution, NUnit assertions, EditMode/PlayMode testing, and TDD workflows. Use PROACTIVELY for test automation, CI/CD pipelines, or test-driven development in Unity.

8 stars

Best use case

unity-testrunner is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Unity Test Framework CLI automation and test writing patterns. Masters batchmode execution, NUnit assertions, EditMode/PlayMode testing, and TDD workflows. Use PROACTIVELY for test automation, CI/CD pipelines, or test-driven development in Unity.

Teams using unity-testrunner should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/unity-testrunner/SKILL.md --create-dirs "https://raw.githubusercontent.com/creator-hian/claude-code-plugins/main/unity-plugin/skills/unity-testrunner/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/unity-testrunner/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How unity-testrunner Compares

Feature / Agentunity-testrunnerStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Unity Test Framework CLI automation and test writing patterns. Masters batchmode execution, NUnit assertions, EditMode/PlayMode testing, and TDD workflows. Use PROACTIVELY for test automation, CI/CD pipelines, or test-driven development in Unity.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

# Unity TestRunner - Automated Testing for Unity

## Overview

Unity Test Framework provides NUnit-based testing with CLI automation for batch execution, CI/CD pipelines, and TDD workflows.

**Core Topics**:
- CLI batchmode test execution (EditMode/PlayMode)
- NUnit assertions and test attributes
- Test assembly configuration (asmdef)
- Result parsing and reporting
- CI/CD pipeline integration

**Foundation Required**: `csharp-plugin:csharp-code-style` (naming conventions, code organization)

**Optional Integrations**:
- `unity-vcontainer`: DI-based test mocking
- `unity-unitask`: Async test patterns
- `unity-async`: Coroutine testing utilities

**Learning Path**: Test basics → CLI automation → Advanced patterns → CI/CD integration

## Quick Start

### Basic Test Structure

```csharp
using NUnit.Framework;

[TestFixture]
public class PlayerServiceTests
{
    private PlayerService mPlayerService;

    [SetUp]
    public void SetUp()
    {
        mPlayerService = new PlayerService();
    }

    [Test]
    public void Initialize_WhenCalled_SetsHealthToMax()
    {
        // Arrange
        int expected = 100;

        // Act
        mPlayerService.Initialize();

        // Assert
        Assert.AreEqual(expected, mPlayerService.Health);
    }

    [TearDown]
    public void TearDown()
    {
        mPlayerService = null;
    }
}
```

### CLI Execution (EditMode)

```powershell
& "C:\Program Files\Unity\Hub\Editor\{VERSION}\Editor\Unity.exe" `
  -batchmode `
  -nographics `
  -projectPath "{PROJECT_PATH}" `
  -runTests `
  -testPlatform editmode `
  -testResults "{TEMP}\results.xml" `
  -logFile "{TEMP}\test.log" `
  -quit
```

### CLI Execution (PlayMode)

```powershell
& "C:\Program Files\Unity\Hub\Editor\{VERSION}\Editor\Unity.exe" `
  -batchmode `
  -projectPath "{PROJECT_PATH}" `
  -runTests `
  -testPlatform playmode `
  -testResults "{TEMP}\results.xml" `
  -logFile "{TEMP}\test.log" `
  -quit
```

Note: PlayMode cannot use `-nographics` (requires scene rendering)

## When to Use

### Trigger Conditions (Proactive)
- Test code (*Tests* path .cs files) created or modified
- TDD workflow in progress (test-first development)
- User explicitly requests "run tests", "execute tests"
- CI/CD pipeline configuration needed
- Test failure debugging required

### Non-Trigger Conditions
- General .cs file modifications without test context
- Configuration or asset file changes only
- Build or deployment tasks without test requirements

## Reference Documentation

### [CLI Automation](references/cli-automation.md)
Complete CLI reference and automation:
- Full CLI option reference table
- Unity Hub path detection (Windows/macOS)
- ProjectVersion.txt parsing
- Environment variable configuration
- CI/CD pipeline templates (GitHub Actions)
- Timeout and log management

### [Test Patterns](references/test-patterns.md)
NUnit patterns and best practices:
- NUnit attribute reference ([Test], [SetUp], [TestCase], etc.)
- EditMode test patterns (pure C#, ScriptableObject)
- PlayMode test patterns (MonoBehaviour, Scene loading)
- Async test patterns (UniTask, IEnumerator)
- Test fixture configuration (asmdef-based)
- Mocking strategies (interface-based)

### [Result Parsing](references/result-parsing.md)
Test result processing:
- NUnit XML result format structure
- PowerShell XML parsing snippets
- Result summary extraction
- Failed test detail extraction
- CI/CD reporting integration

## Key Principles

1. **EditMode First**: Use EditMode for pure logic tests (faster, no scene required)
2. **PlayMode for Integration**: Reserve PlayMode for MonoBehaviour and scene tests
3. **Isolate Dependencies**: Use interfaces for testable architecture
4. **Fast Feedback Loop**: Filter tests during development for quick iteration
5. **Automate in CI/CD**: Configure batchmode execution for continuous testing

## Common Patterns

### Test Filtering

```powershell
# Filter by test name (semicolon-separated)
-testFilter "LoginTest;AuthTest"

# Filter by regex pattern
-testFilter ".*Service.*"

# Filter by category
-testCategory "Unit;Integration"

# Filter by assembly
-assemblyNames "Game.Domain.Tests;Game.Service.Tests"
```

### Unity Version Detection

```powershell
# Parse ProjectVersion.txt
$versionFile = Get-Content "{PROJECT_PATH}/ProjectSettings/ProjectVersion.txt"
$version = ($versionFile | Select-String "m_EditorVersion: (.+)").Matches.Groups[1].Value

# Construct Unity Editor path
$unityExe = "C:\Program Files\Unity\Hub\Editor\$version\Editor\Unity.exe"
```

### Test Assembly Identification

```
Priority pattern for finding test assemblies:
1. {AssemblyName}.Tests.asmdef (same folder or Tests subfolder)
2. Tests/{AssemblyName}/*.asmdef
3. Assets/Tests/EditMode/*.asmdef (fallback)

Example:
  Changed: Assets/Scripts/Domain/LoginService.cs
    -> asmdef: Game.Domain.asmdef
    -> Tests: Game.Domain.Tests.asmdef
    -> Filter: -assemblyNames "Game.Domain.Tests"
```

## Exit Codes

| Exit Code | Meaning | Action |
|-----------|---------|--------|
| 0 | All tests passed | Display summary |
| 2 | Test failures | Display failed test details |
| 1 | Other errors | Check log file for details |

## Result Summary Format

```
Unity Test Results (EditMode)
-----------------------------------
Passed: 15
Failed: 2
Skipped: 1
Duration: 3.45s

Failed Tests:
  1. LoginServiceTests.LoginWithInvalidCredentials_ThrowsException
     -> Expected: ArgumentException
     -> Actual: No exception thrown

  2. AuthTests.TokenExpiry_ShouldInvalidateSession
     -> Assert.AreEqual failed
     -> Expected: False, Actual: True
```

## Platform Considerations

### Windows
```powershell
$unityExe = "C:\Program Files\Unity\Hub\Editor\{VERSION}\Editor\Unity.exe"
```

### macOS
```bash
unityExe="/Applications/Unity/Hub/Editor/{VERSION}/Unity.app/Contents/MacOS/Unity"
```

### CI/CD Environment
```powershell
# Use environment variable for flexibility
$unityExe = $env:UNITY_EDITOR_PATH
if (-not $unityExe) {
    # Fallback to Unity Hub path
}
```

## Error Handling

| Error | Resolution |
|-------|------------|
| Unity Editor path not found | Set `UNITY_EDITOR_PATH` environment variable |
| ProjectVersion.txt missing | Verify Unity project root location |
| Test timeout | Use `-playerHeartbeatTimeout` option (default: 600s) |
| License error | Verify Unity license activation |

## Integration with Other Skills

- **unity-vcontainer**: Configure DI mocks in test fixtures
- **unity-unitask**: Write async tests with UniTask assertions
- **unity-async**: Test coroutine-based logic
- **unity-performance**: Profile test execution performance

Related Skills

unity-vcontainer

8
from creator-hian/claude-code-plugins

VContainer dependency injection expert specializing in IoC container configuration, lifecycle management, and Unity-optimized DI patterns. Masters dependency resolution, scoped containers, and testable architecture design. Use PROACTIVELY for VContainer setup, service registration, or SOLID principle implementation.

unity-unitask

8
from creator-hian/claude-code-plugins

UniTask library expert specializing in allocation-free async/await patterns, coroutine migration, and Unity-optimized asynchronous programming. Masters UniTask performance optimizations, cancellation handling, and memory-efficient async operations. Use PROACTIVELY for UniTask implementation, async optimization, or coroutine replacement.

unity-unirx

8
from creator-hian/claude-code-plugins

UniRx (Reactive Extensions) library expert for legacy Unity projects. Specializes in UniRx-specific patterns, Observable streams, and ReactiveProperty. Use for maintaining existing UniRx codebases. For new projects, use unity-r3 skill instead.

unity-ui

8
from creator-hian/claude-code-plugins

Build and optimize Unity UI with UI Toolkit and UGUI. Masters responsive layouts, event systems, and performance optimization. Use for UI implementation, Canvas optimization, or cross-platform UI challenges.

unity-textmeshpro

8
from creator-hian/claude-code-plugins

TextMeshPro (TMPro) expert for Unity text rendering with advanced typography, performance optimization, and professional text effects. Masters font asset creation, dynamic fonts, rich text formatting, material presets, and text mesh optimization. Use PROACTIVELY for text rendering, font management, localization text, UI text performance, or text effects implementation.

unity-r3

8
from creator-hian/claude-code-plugins

R3 (Reactive Extensions) library expert specializing in modern reactive programming patterns, event-driven architectures, and Observable streams. Masters R3-specific features, async enumerable integration, and Unity-optimized reactive patterns. Use PROACTIVELY for R3 implementation, reactive programming, or MVVM/MVP architecture.

unity-performance

8
from creator-hian/claude-code-plugins

Optimize Unity game performance through profiling, draw call reduction, and resource management. Masters batching, LOD, occlusion culling, and mobile optimization. Use for performance bottlenecks, frame rate issues, or optimization strategies.

unity-networking

8
from creator-hian/claude-code-plugins

Implement multiplayer games with Unity Netcode, Mirror, or Photon. Masters client-server architecture, state synchronization, and lag compensation. Use for multiplayer features, networking issues, or real-time synchronization.

unity-mobile

8
from creator-hian/claude-code-plugins

Optimize Unity games for mobile platforms with IL2CPP, platform-specific code, and memory management. Masters iOS/Android deployment, app size reduction, and battery optimization. Use for mobile builds, platform issues, or device-specific optimization.

unity-csharp-fundamentals

8
from creator-hian/claude-code-plugins

Unity C# fundamental patterns including TryGetComponent, SerializeField, RequireComponent, and safe coding practices. Essential patterns for robust Unity development. Use PROACTIVELY for any Unity C# code to ensure best practices.

unity-collection-pool

8
from creator-hian/claude-code-plugins

Unity Collection Pool expert for GC-free collection management using ListPool, DictionaryPool, HashSetPool, and ObjectPool. Masters memory optimization, pool sizing, and allocation-free patterns. Use PROACTIVELY for collection allocations, GC pressure reduction, temporary list/dictionary usage, or performance-critical code paths.

unity-async

8
from creator-hian/claude-code-plugins

Handle Unity's asynchronous programming patterns including coroutines, async/await, and Job System. Masters Unity's main thread restrictions and threading models. Use when guidance needed on Unity async operations, coroutine optimization, or parallel processing in Unity context.