Logo van Unity Testing

Unity Testing

Organisatie
Nice-Wolf-Studio
unity-testing

Unity 6 testing guide. Use when writing unit tests, integration tests, or doing TDD with Unity Test Framework. Covers Edit Mode and Play Mode tests, NUnit attributes ([Test], [UnityTest], [SetUp], [TearDown]), testing MonoBehaviours and coroutines, and CI/CD integration. Based on Unity 6.3 LTS documentation.

Overzicht

UitgeverNice-Wolf-Studio
Repositoryunity-claude-skills
Skillnaamunity-testing
Sterren
40
Forks
5
Meegeleverde bestanden
1
LicentieMIT
Links
  • Instructies in Markdown

    Een SKILL.md-bestand dat het model laadt wanneer nodig, zodat het alleen tokens kost als een verzoek er daadwerkelijk bij past.

  • Werkt met elk LLM

    AI-skills zijn gewone Markdown, geen aanbiederspecifieke code. Daardoor werken ze met GPT, Claude, Gemini, Grok of een lokaal model.

  • 1 meegeleverde bestanden

    Scripts, sjablonen en referentiemateriaal die het model tijdens het werken kan lezen. Bestanden zijn alleen-lezen en worden nooit uitgevoerd.

  • Open source

    Gepubliceerd door Nice-Wolf-Studio op GitHub. Lees de broninhoud voordat je de skill installeert.

Installatie

Installeer de AI-skill Unity Testing in TypingMind om deze met elke LLM te gebruiken, of voeg de skill toe aan een andere agent die SKILL.md kan lezen.

1

Installeren in TypingMind

TypingMind installeert een skill rechtstreeks vanuit de GitHub-map — het leest SKILL.md, bundelt de bijbehorende bestanden en slaat het resultaat lokaal op.

  1. Open de app en ga naar Plug-ins → Skills.
  2. Kies "Installeren via GitHub".
  3. Plak de onderstaande URL van de skillmap en bevestig.
    https://github.com/Nice-Wolf-Studio/unity-claude-skills/tree/main/skills/unity-testing
  4. Schakel de skill in elke chat in waarin je deze beschikbaar wilt hebben.
Plug-ins → Skills → Nieuwe skill → Via GitHub-URL. Plak vervolgens de map-URL en druk op Doorgaan.
2

Installeren in een andere agent

Elke agent die het Agent Skills-formaat kan lezen, kan deze skill gebruiken — kopieer de map naar de skillmap van die agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Nice-Wolf-Studio/unity-claude-skills.git /tmp/unity-claude-skills
mkdir -p .claude/skills
cp -r /tmp/unity-claude-skills/skills/unity-testing .claude/skills/unity-testing
Start Claude Code na het kopiëren opnieuw op, zodat de nieuwe skill wordt herkend.

Gebruik deze skill in TypingMind

Schakel Unity Testing in een willekeurige chat in TypingMind in en het model doet de rest. De naam en beschrijving staan in de systeemprompt. Zodra een verzoek erbij past, laadt het model zelf de volledige instructies — je hoeft de skill nooit handmatig aan te roepen en deze kost pas tokens wanneer je de skill daadwerkelijk gebruikt.

Het model laadt Unity Testing automatisch zodra een verzoek erbij past.

Werkt met elk AI-model

AI-skills zijn gewone Markdown-instructies in plaats van aanbiederspecifieke code. Daardoor is Unity Testing niet gebonden aan het model waarvoor de skill is geschreven. Installeer de skill één keer in TypingMind en gebruik deze met GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama of een lokaal model dat je zelf draait — allemaal met je eigen API-sleutels.

  • Alleen geladen wanneer nodig

    De systeemprompt bevat alleen de naam en beschrijving. De instructies worden bij het eerste bijpassende verzoek opgehaald, dus een ongebruikte skill kost niets.

  • Wissel van model tijdens een chat

    Omdat de skill uit instructies bestaat en niet uit code, blijft deze werken als je van model wisselt — het volgende model leest hetzelfde SKILL.md-bestand.

Skillinstructies

Dit is de inhoud van SKILL.md die het model laadt. Lees deze vóór de installatie — een skill bestaat uit instructies die je model zal volgen.

Unity Test Framework

Test Framework Overview

The Unity Test Framework (UTF) is Unity's built-in testing solution, integrating a custom version of NUnit (based on NUnit 3.5) adapted for Unity. It enables testing C# code in Edit Mode, Play Mode, and on target platforms (Standalone, Android, iOS).

UTF extends NUnit with Unity-specific attributes ([UnityTest], [UnitySetUp], [UnityTearDown]) that support coroutines, yield instructions, and frame-based execution.

Key capabilities:

  • Edit Mode tests for editor extensions and pure logic
  • Play Mode tests for gameplay, physics, and coroutine-based code
  • Standalone player test builds for platform-specific validation
  • Command-line execution for CI/CD pipelines
  • NUnit XML result output

Source: Unity Test Framework 2.0 Manual


Setup and Configuration

Installing the Test Framework

UTF ships with Unity by default. Open the Test Runner via Window > General > Test Runner.

Creating a Test Assembly

Test code must live in its own assembly definition (.asmdef) that references NUnit.

Create via Window > General > Test Runner (click Create a new Test Assembly Folder) or Assets > Create > Testing > Test Assembly Folder.

This creates a Tests folder with an .asmdef file preconfigured with references to:

  • nunit.framework.dll
  • UnityEngine.TestRunner
  • UnityEditor.TestRunner (Edit Mode only)

Edit Mode Assembly Definition (.asmdef)

json
{
    "name": "Tests",
    "references": [
        "UnityEngine.TestRunner",
        "UnityEditor.TestRunner"
    ],
    "includePlatforms": ["Editor"],
    "defineConstraints": ["UNITY_INCLUDE_TESTS"],
    "autoReferenced": false
}

Play Mode Assembly Definition (.asmdef)

json
{
    "name": "Tests.PlayMode",
    "references": [
        "UnityEngine.TestRunner",
        "UnityEditor.TestRunner",
        "MyGameAssembly"
    ],
    "includePlatforms": [],
    "optionalUnityReferences": ["TestAssemblies"],
    "defineConstraints": ["UNITY_INCLUDE_TESTS"],
    "autoReferenced": false
}

Important: To test your game code, add a reference to the assembly containing the code under test in the references array.

Source: Creating Test Assemblies


Edit Mode vs Play Mode Tests

AspectEdit ModePlay Mode
Execution contextEditorApplication.update callback loopCoroutine on a MonoBehaviour
Editor accessFull Editor + game codeGame code only (unless in Editor)
Coroutine supportyield return null skips one updateFull yield instructions (WaitForSeconds, etc.)
Platform targetsEditor onlyEditor Play Mode + standalone players
Use casesEditor extensions, pure logic, serializationPhysics, gameplay, MonoBehaviour lifecycle
Assembly platform"includePlatforms": ["Editor"]"includePlatforms": []

When to use Edit Mode:

  • Testing editor tools, custom inspectors, ScriptableObject logic
  • Pure C# logic that does not depend on runtime systems
  • Tests that need access to UnityEditor APIs

When to use Play Mode:

  • Testing MonoBehaviour lifecycle (Awake, Start, Update)
  • Physics interactions requiring WaitForFixedUpdate
  • Coroutine and async workflows
  • Scene loading and object instantiation at runtime

Best practice: Use NUnit [Test] instead of [UnityTest] unless you need yield instructions. [Test] runs faster since it does not require coroutine overhead.

Source: Edit Mode vs Play Mode Tests


Writing Tests

Create test scripts via Assets > Create > Testing > C# Test Script or using the Test Runner's Create a new Test Script button.

Basic Test Structure

csharp
using NUnit.Framework;

[TestFixture]
public class HealthSystemTests
{
    private HealthSystem _health;

    [SetUp]
    public void SetUp() => _health = new HealthSystem(maxHealth: 100);

    [TearDown]
    public void TearDown() => _health = null;

    [Test]
    public void TakeDamage_ReducesHealth()
    {
        _health.TakeDamage(30);
        Assert.AreEqual(70, _health.CurrentHealth);
    }

    [Test]
    public void TakeDamage_CannotGoBelowZero()
    {
        _health.TakeDamage(150);
        Assert.AreEqual(0, _health.CurrentHealth);
    }

    [Test]
    public void Heal_IncreasesHealth()
    {
        _health.TakeDamage(50);
        _health.Heal(20);
        Assert.AreEqual(70, _health.CurrentHealth);
    }
}

NUnit Attributes Reference

AttributePurpose
[Test]Marks a method as a synchronous test
[TestFixture]Marks a class as containing tests
[SetUp]Runs before each test method
[TearDown]Runs after each test method
[OneTimeSetUp]Runs once before all tests in the fixture
[OneTimeTearDown]Runs once after all tests in the fixture
[TestCase(args)]Parameterized test with inline data
[Values(args)]Provides values for a test parameter
[Category("name")]Categorizes tests for filtering
[Ignore("reason")]Skips a test with a reason
[Timeout(ms)]Sets a timeout for the test

Unity-Specific Attributes

AttributePurpose
[UnityTest]Coroutine-based test supporting yield instructions
[UnitySetUp]Coroutine-based setup (supports yield)
[UnityTearDown]Coroutine-based teardown (supports yield)
[RequiresPlayMode]Forces test to run in Play Mode (true) or Edit Mode (false)
[UnityPlatform]Restricts test to specific platforms
[TestMustExpectAllLogs]Requires all log messages to be expected
[PrebuildSetup]Runs setup before player build
[PostBuildCleanup]Runs cleanup after player build
[ConditionalIgnore]Conditionally ignores tests
[TestRunCallback]Subscribes to test progress updates

Common Assertions

csharp
Assert.AreEqual(expected, actual);           // Equality
Assert.IsTrue(condition);                    // Boolean
Assert.IsNotNull(obj);                       // Null check
Assert.Throws<ArgumentException>(() => F()); // Exception
Assert.AreEqual(1.0f, actual, 0.01f);       // Float tolerance
StringAssert.Contains("sub", actualString);  // String
CollectionAssert.Contains(list, item);       // Collection

See references/test-framework.md for the full assertion API reference.

Source: Creating Tests


Testing MonoBehaviours

csharp
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
using System.Collections;

[TestFixture]
public class PlayerControllerTests
{
    private GameObject _playerObject;
    private PlayerController _player;

    [UnitySetUp]
    public IEnumerator SetUp()
    {
        _playerObject = new GameObject("Player");
        _player = _playerObject.AddComponent<PlayerController>();
        yield return null; // Wait one frame for Awake/Start
    }

    [UnityTearDown]
    public IEnumerator TearDown()
    {
        Object.Destroy(_playerObject);
        yield return null; // Wait for destruction
    }

    [UnityTest]
    public IEnumerator Player_MovesForward_WhenInputApplied()
    {
        var startPos = _player.transform.position;
        _player.Move(Vector3.forward);

        yield return new WaitForFixedUpdate();

        Assert.Greater(_player.transform.position.z, startPos.z);
    }
}

Testing Coroutines and Async

Edit Mode UnityTest (yields in EditorApplication.update)

csharp
[UnityTest]
public IEnumerator EditorUtility_WhenExecuted_ReturnsSuccess()
{
    var utility = RunEditorUtilityInTheBackground();
    while (utility.isRunning) { yield return null; }
    Assert.IsTrue(utility.isSuccess);
}

Play Mode UnityTest (coroutine-based)

csharp
[UnityTest]
public IEnumerator GameObject_WithRigidBody_WillBeAffectedByPhysics()
{
    var go = new GameObject();
    go.AddComponent<Rigidbody>();
    var originalPosition = go.transform.position.y;
    yield return new WaitForFixedUpdate();
    Assert.AreNotEqual(originalPosition, go.transform.position.y);
}

Available Yield Instructions (Play Mode)

Yield InstructionEffect
yield return nullSkip one frame
yield return new WaitForSeconds(t)Wait for t seconds (scaled time)
yield return new WaitForSecondsRealtime(t)Wait for t real-time seconds
yield return new WaitForFixedUpdate()Wait for next physics update
yield return new WaitForEndOfFrame()Wait until end of frame
yield return new WaitUntil(() => cond)Wait until condition is true
yield return new WaitWhile(() => cond)Wait while condition is true

Testing with LogAssert

csharp
[Test]
public void LogWarning_IsExpected()
{
    LogAssert.Expect(LogType.Warning, "Expected warning message");
    Debug.LogWarning("Expected warning message");
}

Use LogAssert.NoUnexpectedReceived() to assert no unexpected log messages were emitted. Debug.LogError and Debug.LogException cause automatic test failure unless expected.


Common Test Patterns

Arrange-Act-Assert (AAA)

csharp
[Test]
public void Inventory_AddItem_IncreasesCount()
{
    // Arrange
    var inventory = new Inventory(maxSlots: 10);
    var item = new Item("Sword");

    // Act
    inventory.Add(item);

    // Assert
    Assert.AreEqual(1, inventory.Count);
}

Parameterized Tests

csharp
[TestCase(100, 30, 70)]
[TestCase(100, 100, 0)]
[TestCase(100, 150, 0)]
[TestCase(50, 10, 40)]
public void TakeDamage_CalculatesCorrectly(int maxHp, int damage, int expectedHp)
{
    var health = new HealthSystem(maxHp);
    health.TakeDamage(damage);

    Assert.AreEqual(expectedHp, health.CurrentHealth);
}

Testing Exceptions

csharp
[Test]
public void Inventory_AddNull_ThrowsException()
{
    var inventory = new Inventory(maxSlots: 10);

    Assert.Throws<ArgumentNullException>(() =>
    {
        inventory.Add(null);
    });
}

Scene-Based Testing

csharp
[UnityTest]
public IEnumerator Scene_Loads_Successfully()
{
    SceneManager.LoadScene("GameScene", LoadSceneMode.Single);
    yield return new WaitUntil(() => SceneManager.GetActiveScene().name == "GameScene");
    Assert.IsTrue(SceneManager.GetActiveScene().isLoaded);
}

Testing with Fakes (Dependency Injection)

csharp
public class FakeAudioService : IAudioService
{
    public bool PlaySoundCalled { get; private set; }
    public void PlaySound(string name) => PlaySoundCalled = true;
}

[Test]
public void Attack_PlaysSound()
{
    var fakeAudio = new FakeAudioService();
    var weapon = new Weapon(fakeAudio);
    weapon.Attack();
    Assert.IsTrue(fakeAudio.PlaySoundCalled);
}

Running Tests

From the Test Runner Window

Open Window > General > Test Runner. Toggle EditMode / PlayMode checkboxes. Run tests via Run All, Run Selected, double-click, or right-click context menu. Filter using the search box or result icon buttons.

From the Command Line (CI/CD)

bash
# Run Edit Mode tests
Unity -runTests -batchmode -projectPath /path/to/project \
  -testPlatform EditMode -testResults /path/to/results.xml

# Run Play Mode tests
Unity -runTests -batchmode -projectPath /path/to/project \
  -testPlatform PlayMode -testResults /path/to/results.xml

# Run filtered tests by name and category
Unity -runTests -batchmode -projectPath /path/to/project \
  -testFilter "HealthSystemTests" -testCategory "Unit;Integration" \
  -testResults /path/to/results.xml

Command-Line Arguments Reference

ArgumentDescription
-runTestsRequired flag to run tests
-testPlatformEditMode, PlayMode, or any BuildTarget value
-testFilterSemicolon-separated test names or regex pattern; prefix with ! to negate
-testCategorySemicolon-separated category names; prefix with ! to negate
-testResultsOutput path for NUnit XML results (default: project root)
-testNamesFull test names in FixtureName.TestName format
-assemblyNamesFilter by specific test assembly names
-batchmodeRun without UI (required for CI/CD)
-runSynchronouslyExecute all tests in one editor update (EditMode only)
-playerHeartbeatTimeoutSeconds to wait for player heartbeat (default: 600)

IDE Integration

JetBrains Rider supports running Unity tests directly from the IDE with full debugging support.

Source: Running Tests, Command Line Reference


Anti-Patterns

1. Using [UnityTest] when [Test] suffices

[UnityTest] adds coroutine overhead. Use [Test] for synchronous logic.

csharp
// BAD - unnecessary coroutine overhead
[UnityTest]
public IEnumerator Add_ReturnsSum()
{
    var result = Calculator.Add(2, 3);
    yield return null;
    Assert.AreEqual(5, result);
}

// GOOD - simple synchronous test
[Test]
public void Add_ReturnsSum()
{
    var result = Calculator.Add(2, 3);
    Assert.AreEqual(5, result);
}

2. Not cleaning up GameObjects

Leaked objects contaminate other tests. Always destroy GameObjects in [UnityTearDown] or [TearDown]. Create objects in setup, destroy in teardown.

3. Testing private methods directly

Test through public interfaces. If you must, use [assembly: InternalsVisibleTo("Tests")].

4. Hardcoding time-based waits

Use WaitUntil or WaitForFixedUpdate instead of arbitrary WaitForSeconds.

csharp
// BAD - brittle, slow
yield return new WaitForSeconds(5f);
Assert.IsTrue(enemy.IsDead);

// GOOD - deterministic
yield return new WaitUntil(() => enemy.IsDead);
Assert.IsTrue(enemy.IsDead);

5. Tests depending on execution order

Each test must be independent. Use [SetUp] / [TearDown] to establish clean state.

6. Ignoring log errors

Unexpected Debug.LogError calls cause test failures by default. Use LogAssert.Expect() for expected errors or LogAssert.ignoreFailingMessages = true only when necessary.

7. Placing tests in production assemblies

Test assemblies use UNITY_INCLUDE_TESTS define constraint and are excluded from production builds. Never mix test code with game code assemblies.


Related Skills

  • unity-scripting -- C# scripting fundamentals, MonoBehaviour lifecycle, coroutines
  • unity-editor-tools -- Custom editors, inspectors, and editor extensions

Additional Resources

Meegeleverde bestanden

Het model leest deze bestanden wanneer nodig terwijl de skill geladen is. Ze worden beschikbaar gesteld als leesbare bestanden en worden nooit uitgevoerd.

Veelgestelde vragen

Wat doet de AI-skill Unity Testing?

Unity 6 testing guide. Use when writing unit tests, integration tests, or doing TDD with Unity Test Framework. Covers Edit Mode and Play Mode tests, NUnit attributes ([Test], [UnityTest], [SetUp], [TearDown]), testing MonoBehaviours and coroutines, and CI/CD integration. Based on Unity 6.3 LTS documentation.

Waarom Unity Testing gebruiken in TypingMind?

Omdat je deze skill één keer installeert en met elk model kunt gebruiken. Unity Testing bestaat uit gewone Markdown in plaats van aanbiederspecifieke code. Dezelfde skill werkt dus met GPT-5, Claude, Gemini, Grok of een lokaal model, en je kunt midden in een chat van model wisselen zonder dat de skill niet meer werkt. TypingMind werkt met je eigen API-sleutels, dus je betaalt aanbieders rechtstreeks in plaats van een abonnement per gebruikersplek. Je skills en chats blijven in je eigen opslag.

Hoe installeer ik Unity Testing in TypingMind?

Open Plug-ins → Skills → Installeren vanaf GitHub in TypingMind en plak https://github.com/Nice-Wolf-Studio/unity-claude-skills/tree/main/skills/unity-testing. TypingMind leest het bestand SKILL.md, bundelt de bijbehorende bestanden en installeert het geheel als een skill die je per chat kunt inschakelen.

Welke AI-modellen kunnen Unity Testing gebruiken?

Elk model dat je in TypingMind koppelt. AI-skills bestaan uit gewone Markdown-instructies in plaats van aanbiederspecifieke code. GPT, Claude, Gemini, Grok en lokale modellen kunnen deze skill dus allemaal laden wanneer een verzoek erbij past.

Hoeveel AI-modellen kan ik met Unity Testing gebruiken?

Zoveel als je wilt. Zolang een model skills ondersteunt, kun je Unity Testing ermee gebruiken: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama en meer. Allemaal in TypingMind met je eigen API-sleutels.

Is de AI-skill Unity Testing gratis?

Ja. Deze skill is door Nice-Wolf-Studio op GitHub gepubliceerd onder de licentie MIT. Je betaalt alleen je eigen AI-aanbieder voor de tokens die je gebruikt.

Wat zijn AI-skills?

Een AI-skill is een herbruikbare bundel instructies die een AI-model leert hoe het één specifieke taak moet uitvoeren. Deze volgt het open Agent Skills-formaat: een bestand met de naam SKILL.md met een naam en beschrijving, plus eventuele scripts, sjablonen of referentiebestanden die het model nodig heeft. Het model leest de instructies alleen als je verzoek bij de skill past. Een geïnstalleerde skill kost dus niets zolang deze niet wordt gebruikt.

Waarin verschillen AI-skills van plug-ins of MCP-servers?

Een plug-in of MCP-server geeft een model nieuwe tools om aan te roepen: code die ergens wordt uitgevoerd en een resultaat teruggeeft. Een AI-skill geeft het model juist kennis en een werkwijze: hoe het een taak moet aanpakken, welke stappen het moet volgen en hoe goede uitvoer eruitziet. Skills bestaan uit gewone Markdown en hebben dus geen server, API-sleutel of runtime nodig. Ze werken met elk model.

Toon alles

Maak nu je eigen AI-werkruimte

Schrijf je in voor onze nieuwsbrief en blijf op de hoogte van nieuwe functies en toekomstige weggeefacties 👇