Skip to content

Contributing Testing Patterns

github-actions[bot] edited this page Nov 13, 2026 · 18 revisions

Testing "Impossible" State Patterns

This guide documents patterns for testing states that "should never happen" but could occur in production. These tests catch edge cases that defensive programming must handle gracefully.

Reuse the packaged test helpers

Add WallstopStudios.UnityHelpers.TestSupport to your test assembly's references, keep UNITY_INCLUDE_TESTS in its define constraints, and reference nunit.framework.dll when overrideReferences is enabled. The support assembly is disabled outside test compilation; it does not require the package's Tests/Core sources.

Derive synchronous NUnit fixtures from UnityObjectTrackingTestBase in WallstopStudios.UnityHelpers.TestSupport. Track, TrackRange, and CreateScriptableObject<T> register transient objects owned by the test. Setup starts a scope; teardown destroys its objects immediately in reverse order, including after a failed assertion. Persistent Editor assets are refused. Use a coroutine lifecycle fixture when deferred destruction or frame boundaries are part of the behavior under test. Do not manually destroy shared assets or transfer tracked objects to another owner.

TrackDisposable<T> registers a managed resource for cleanup before tracked Unity objects are destroyed. Resources are disposed in reverse registration order, and registering the same instance again does not dispose it twice. Null resources are ignored. A cleanup failure still releases the remaining resources and objects, then fails the test. Cleanup closes the scope before callbacks run, so callbacks cannot reenter cleanup or register more resources.

AllocationProbe.IgnoreWhenUnmeasurable() requires a known allocation to be observable before using Unity's allocation constraint. ProfilerAllocationCounter.Measure counts current-thread allocation events, warms the action first, and rejects truncated results and invalid bounds. Run a retained-allocation positive control before interpreting a zero count. The count is events, not allocated bytes; neither helper makes an unsupported player measurable.

Run script checks through Python

Use npm run lint:repo -- --only <id> or npm run validate:tests:fast -- --only <id> for focused checks. Both commands run the locked, strictly typed Python runner through uv. Add --list to inspect the available ids and --jobs 1 to run them serially. The runners execute every selected check, retain failures, and preserve registry order in the final report. Checks that rewrite shared inputs run exclusively before shared work.

The lint, contract, and hook check definitions live in scripts/lint-checks.json, scripts/contracts-checks.json, and scripts/hooks-checks.json. Keep commands and required completion markers with their check. Empty registries, duplicate ids, unknown fields, and mistyped exclusivity policies fail before execution. Register new Python sources in scripts/python~/pyproject.toml; npm run lint:python runs Ruff, mypy, and Pyright.

The npm entry points resolve exact npm run <name> commands directly from package.json, avoiding an npm process for each check. Raw shell commands retain their original behavior. The Node entry points remain compatibility launchers for existing callers and imports. Use npm run test:check-registries for selection and CLI controls and npm run test:check-runner for process, concurrency, and completion controls.

Timing reports require durations for executed NUnit results, including passed, failed and inconclusive cases. Missing or blank durations fail reporting before fixture budgets are evaluated. Explicit zero durations remain valid; skipped and older result records without an outcome retain the zero-duration fallback.

npm run lint:unity-file-naming and npm run test:lint-unity-file-naming run the typed Python checker and its retained fixture corpus directly. The PowerShell entry points remain compatible; the linter wrapper defaults to the caller's working directory and accepts -RepoRoot and -StagedOnly. Direct Python calls default to this checkout and accept --repo-root and --staged-only. Staged selection is anchored to the requested Git root and includes renames. It reads Git index blobs, so unstaged corrections cannot hide a committed naming violation. Comments and literal text do not declare types or suppress findings. The check recognizes the listed direct Unity base classes; it does not resolve arbitrary user-defined inheritance chains. The compatibility test launcher accepts -TestFilter for a pytest name expression; it preserves the pytest exit status, including an empty selection.

Standalone players using -nographics can omit material texture state. Keep geometry, UV, animation, and lifecycle assertions active in those players. Texture-state inspections require the Editor or a graphics backend other than GraphicsDeviceType.Null; qualify those assertions with a graphics-enabled batch player as well.

Isolated migration compiler tests

The Odin compiler fixture rewrites a small runtime consumer asset rather than the shared test helpers. Its graph includes the asset assembly, a runtime caller assembly, and the dedicated WallstopStudios.UnityHelpers.Tests.Editor.OdinCompilation test assembly. The fixture requires all three to compile and separately breaks runtime and editor member access. Keep the consumer targets out of shared test assembly references: migrating a shared helper recompiles its entire dependent test graph on every case.

Keep large unordered oracles linear

NUnit 3.5 unordered equivalence checks can become quadratic for large shuffled collections. For map views, compare every pair with an independent Dictionary, check key uniqueness and membership with a HashSet, and verify the exact count. Compare values with a frequency table so duplicates retain their multiplicity. A value HashSet alone would lose that coverage. IntMapTests.AssertViewsMatch follows this pattern across removal, growth, clear and refill. Keep ordered assertions when order is part of the API contract.

Use typed byte-span equality for large frozen payloads. NUnit's object-based byte comparisons can dominate an IL2CPP correctness case. WProtoBenchmarkCorpus.AssertBytesEqual compares every byte in order, including the exact length, without copying the writer's span. Keep independent controls for different lengths and first, middle, and last byte mutations. Preserve the frozen workloads and timeout when reducing assertion cost.

Configure Release before initial import

Configure invocations request Release code optimization at editor startup, matching the test and build invocations. Setting it inside the configure method is too late for the initial import: even a warm project first recompiles in Debug, then recompiles again for Release tests. Fresh generated Unity 6 projects also seed requested Standalone scripting defines before the first editor import. Earlier editors keep define configuration in their configure pass. Existing player settings remain intact; the configure pass still merges requested defines and verifies the final settings.

Keep memory-only cleanup outside asset batches

When a fixture explicitly imports a known path with ImportAsset or SaveAndReimport, call ExecuteWithImmediateImport(..., refreshBefore: false) to pause the batch without first scanning the entire project. The default remains a synchronous pre-refresh. Keep that default for operations that rely on discovering arbitrary pending filesystem changes. Asset creation, import assertions, and final folder cleanup must still run; the option only removes the preceding global scan.

CommonTestBase.DestroyTrackedObjects opens an asset editing batch only when a tracked object has an asset path. Memory-only cleanup destroys objects immediately without refreshing the asset database. Mixed cleanup retains its batch around every destruction callback, and an existing outer batch remains active. Keep native coverage for these paths and for deferred asset deletion when changing shared cleanup. CleanupTrackedFoldersAndAssets also leaves the database untouched when no paths are tracked.

Isolate inputs when deferring asset cleanup

When a fixture defers asset deletion until its final cleanup, give each case its own input folder. A shared input folder lets later searches discover earlier cases' assets and repeat imports or transformations. SpriteCropperAdditionalTests uses the NUnit case ID for its folder and requires exact input and processing counts. Keep deferred deletion so isolation does not add a database refresh after every case.

Give each parameterized case a stable identity

For a ValueSource that supplies objects or structs, provide a deterministic display value, such as a ToString() override returning the scenario description. Check that the registered scenarios have distinct values. Read the resulting NUnit XML to verify the actual fullnames; counting test leaves alone cannot distinguish scenarios whose display values collide. The Unity result verifier rejects duplicate fullnames for singleton metadata scenarios.

Access real implementation internals

Production code contains no test-only methods, callbacks, state capture, timing latches, or conditional execution paths. Names such as ForTest, ForTesting, ForTests, and TestHooks are prohibited in shipped implementation code and generated production source. Tests use existing operations and state through internal visibility and friend assemblies.

  • Promote the actual method or field needed by a fixture; remove forwarding wrappers and duplicate diagnostics.
  • Keep fixture setup, state snapshots, reset helpers, and deterministic inputs under Tests/.
  • Exercise real file ownership, cancellation, layout, and lifecycle operations. Do not add callbacks to pause production execution or suppress editor actions.
  • State the limits of phase tests: testing publication after staging does not by itself prove scheduling through the entire public asynchronous operation.
  • Keep timing observations in test-owned entry points. A warmed registration call cannot replace a first-registration measurement.

This removes the released test APIs AttributeMetadataCache.ForceRebuildForTests, WProtoDeclaredRootProvider.Unregister, and UnityMainThreadDispatcher.CreateTestScope. Package fixtures use internal implementation state; external consumer tests exercise public operations instead. Relational metadata changes invalidate lookups through SetMetadata, and the assigner rebuilds them on first use.

The production-hook gate checks forbidden identifiers and explicit test-only markers with positive controls. Review still checks suffix-free injection and instrumentation. Legitimate discovery of test assemblies and UI suppression during automated editor runs remain supported. The ValidationRun loader overload also remains: automatic validation uses it to resolve live prefab-stage roots before falling back to asset loading. Tests use real asset targets and implementation phases.

Preserve editor assets during fixtures

Known-folder cleanup opens an asset-editing batch only when it finds a matching, unprotected folder to remove. An empty cleanup leaves unrelated pending imports untouched. Real deletions retain their final refresh; cleanup inside an existing batch preserves that batch's ownership.

Use a unique directory for generated fixture assets. Register only paths the fixture owns, then explicitly call CleanupTrackedFoldersAndAssets. Batched fixtures must transfer their tracked paths before calling the base OneTimeTearDown, which removes the deferred paths. Check the database, directory and importer metadata after cleanup.

Create fixture roots through ExecuteWithImmediateImport before using them in a batch. Creating a directory on disk while its import is deferred can make Unity create a second folder with a numeric suffix. For a root containing a unique identifier, EditorAssetFolderAssertions.AssertUniqueRootRemoved also checks for these siblings. Keep this assertion in fixture teardown so passing test cases cannot hide a cleanup failure.

Drain deferred asset actions between independent import-heavy test cases. A fixture must not accumulate their unrelated import batches into one recursive-change window. Reset that window only after draining, so a genuine loop within one case still fails visibly.

When a fixture exercises a tool that persists a shared settings or cache asset, use the test-only EditorAssetFileScope with those exact asset paths. Capture it before the tool runs and dispose it after fixture teardown, including failure paths. It restores existing file and metadata bytes, removes newly created assets, and removes only newly created empty parents. It preserves unrelated sibling assets. Clear the tool's cached singleton reference afterward.

Inspect full NUnit results as well as leaf counts. A fixture teardown failure can leave all individual test cases passing while the run itself fails.

PR and push version jobs activate once, then run the selected modes concurrently in separate persistent projects and owned source worktrees. Compiler fixtures can rewrite their own sources without changing another mode's inputs. The coordinator verifies cache ownership and repository identity before restoring a worktree; unknown paths are preserved. The two main EditMode shards retain separate editor caches. Their compiler and migration phases run in another project at the same time; all three workers must pass. PlayMode uses its own project. Windows workers use private desktops so concurrent editors do not share menu and window resources. Worker output uses plain text; raw Unity logs remain available. Cache pruning runs once during preparation. All projects retire legacy collectors before any parallel worker starts; workers do not prune sibling projects. Each worker verifies the session's version, editor path, job identity and live owner before reusing activation. At most five workers run at once, so both main EditMode shards, the isolated compiler phases, Standalone and PlayMode can start together. The WProto-only worker waits for a free slot. The coordinator waits for every worker and kills timed-out worker trees before central license return. Mode receipts record elapsed time and all outcomes. The existing per-mode NUnit, redaction and artifact gates still apply. Manual diagnostic dispatches keep the serial path.

Repository check processes disable automatic Python bytecode cache writes. This keeps parallel checks from changing inputs while the acceptance runner records its strict source census.

The coordinator accepts --editmode-shards 2 to divide the selected EditMode assembly profile into two deterministic groups. Each group uses its own project and source worktree. Fixtures stay within their assembly, and compiler and migration phases retain the complete original profile. Use --max-workers 5 when the runner has capacity for the extra editor; the default remains four. One EditMode shard remains the default for other callers. --artifacts-root can select a short local capture directory when the checkout path approaches Windows file API limits.

The second shard captures evidence in a short sibling directory, then the coordinator moves it under the primary artifact's shards/1 directory after its worker closes. The primary raw XML is retained as shards/main-results.xml. Combined publication requires both workers to finish successfully, positive passing cases, consistent root and leaf counts, known outcomes, no failed suites, disjoint assembly sets, and no assemblies outside the selection. Every selected assembly is assigned once; Unity can omit assemblies disabled by package or define constraints, such as Odin tests in a core project. Failed shards fail EditMode. Combined duration sums test execution across workers; use the mode receipt's elapsed time for wall time. Compare complete case identities, skips, native process health and cold versus warm caches before drawing a timing conclusion.

The isolated migration contract phase runs the API, backup recovery, import verification and apply-record fixtures in one editor invocation. The compiler fixture and domain-reloading apply fixture retain separate invocations. Each group requires every named fixture, rejects skipped or missing cases, and checks root and suite failures.

Identify the Unity Test Framework used by a run

The local test-project builder, CI builder and package exporter read the framework request from .github/unity-test-framework.json. Unity 2021/2022 use the compatible registry request. Unity 6 supplies a core package tied to the editor, so the request alone does not identify what ran. See Unity's core-package policy. Keep the separate NUnit 3.5 compiler floor and historical host witnesses unchanged.

Generated test projects include an editor-only collector. Persistent project paths include a compact fingerprint of the test leg, collector source, assembly definition and framework policy. Revisions with different collector inputs use separate project Libraries and retain the shared package-download cache. Explicit project-path overrides keep their requested location. The runner retires only the exact known collector files left by the initial unpublished implementation in legacy caches. It refuses unknown or linked files and active editors, retains original bytes before removal, and preserves unrelated assets, parent folders and their metadata.

CI gives each editor invocation a fresh framework/<capture-id> directory at the leg artifact root, independent of nested log paths. Each invocation retains its own log and process diagnostics before retry paths can overwrite them. Its record binds those copies to the project and process. It retains the manifest before launch, then captures the resolved manifest and lock, framework package metadata and C# source files, and the loaded editor runner, runtime runner and NUnit DLLs, plus available PDBs. Package sources use short numbered entries in sources.zip; the inventory retains their original package-relative paths. Schema 3 checks every archive entry against its recorded length and SHA-256 and rejects missing, duplicate or unlisted entries. Historical schema 2 snapshots with loose source files remain readable. This keeps generated compiler and evidence paths within Windows file API limits. Each domain snapshot records its process, project, Unity version, loaded module IDs and file hashes. The readback checks those IDs against the retained DLL bytes and rejects missing or changed evidence. Repeated domain reloads produce separate snapshots. A capture error fails the evidence check.

The shared runtime test base applies its existing optional allocator-warning policy to native log callbacks as well as managed logs. It processes explicit expectations first and leaves unrelated warnings and all errors subject to the strict log check.

For a manually launched generated project, pass -uhFrameworkEvidenceDirectory <new-path> to collect the same snapshots. These startup records identify the loaded modules and source bytes observed in that domain. They do not prove a clean rebuild, map every framework source to compiler inputs, qualify CLI result semantics, or establish native process health. Inspect complete NUnit roots and suites, raw process receipts and expected inconclusive outcomes separately. A green XML report cannot explain an abnormal native exit.

Run npm run test:unity-modes for process overlap, cancellation, session identity and source-isolation controls. These controls use a labeled worker fixture; they do not replace native mode qualification.

Run npm run test:unity-framework for manifest controls and compiled host collector controls. The host controls use labeled API shims; native framework qualification still requires the supported Unity matrix and controls for timeout, teardown and interrupted PlayMode behavior.

A recognized Package Manager failure before a fresh configure marker or NUnit result retains the existing single retry. The final invocation still requires complete framework evidence.

Source validation must find its subjects

Package source scans resolve the owning package from its assembly, then use the source file path for an Assets installation. Validate the manifest's exact package name and the Tests directory; a path containing the package name can identify a nested dependency instead. Naming and assembly validators share this resolver.

Fail if the expected fixture source is absent, the source set is empty, or a file cannot be read. An inconclusive scan does not prove that naming rules passed. Resolver controls cover nested dependencies, wrong manifests and the source-path fallback.

Why Test "Impossible" States

Production code encounters situations that seem impossible during development:

  • Destroyed Unity Objects: Objects destroyed by external code, scene unloading, or domain reloads
  • Null References: References that "can't be null" become null due to serialization issues, race conditions, or user error
  • Invalid Enum Values: Casting arbitrary integers to enums produces values not defined in the enum
  • Corrupted Serialization State: Save files edited by users, version mismatches, or truncated data
  • Overflow Conditions: Extreme values that exceed expected ranges

Testing these scenarios ensures code fails gracefully rather than crashing or corrupting data.

Destroyed Unity Objects

Unity objects can be destroyed at any time by external systems. Code must handle the "fake null" state where an object reference is not null in C# terms but returns true for Unity's null check.

Pattern: Test Behavior After DestroyImmediate

[Test]
public void GetGameObjectHandlesDestroyedComponent()
{
    GameObject go = Track(new GameObject("Test", typeof(SpriteRenderer)));
    SpriteRenderer spriteRenderer = go.GetComponent<SpriteRenderer>();

    Object.DestroyImmediate(spriteRenderer); // UNH-SUPPRESS: Test verifies behavior after component destruction

    GameObject result = spriteRenderer.GetGameObject();

    Assert.IsTrue(result == null, "Should return null for destroyed component");
}

Real Example: UnityExtensionsBasicTests.cs

From /workspaces/com.wallstop-studios.unity-helpers/Tests/Runtime/Extensions/UnityExtensionsBasicTests.cs:

[Test]
public void GetCenterUsesCenterPointOffsetWhenAvailable()
{
    GameObject go = Track(new GameObject("CenterPointTest", typeof(CenterPointOffset)));

    go.transform.position = new Vector3(5f, 5f, 0f);
    CenterPointOffset offset = go.GetComponent<CenterPointOffset>();
    offset.offset = new Vector2(3f, 4f);

    Assert.AreEqual(offset.CenterPoint, go.GetCenter());

    Object.DestroyImmediate(offset); // UNH-SUPPRESS: Test verifies behavior after component destruction
    Assert.AreEqual((Vector2)go.transform.position, go.GetCenter());
}

This test verifies that GetCenter() falls back to the GameObject's transform position when the CenterPointOffset component is destroyed.

Real Example: ObjectHelperTests.cs

From /workspaces/com.wallstop-studios.unity-helpers/Tests/Runtime/Helper/ObjectHelperTests.cs:

[UnityTest]
public IEnumerator GetGameObject()
{
    GameObject go = Track(new GameObject("Test", typeof(SpriteRenderer)));
    SpriteRenderer spriteRenderer = go.GetComponent<SpriteRenderer>();

    GameObject result = go.GetGameObject();
    Assert.AreEqual(result, go);
    result = spriteRenderer.GetGameObject();
    Assert.AreEqual(result, go);

    Object.DestroyImmediate(spriteRenderer); // UNH-SUPPRESS: Test verifies behavior after component destruction
    result = spriteRenderer.GetGameObject();
    Assert.IsTrue(result == null);
    result = go.GetGameObject();
    Assert.AreEqual(result, go);

    Object.DestroyImmediate(go); // UNH-SUPPRESS: Test verifies behavior after GameObject destruction
    result = spriteRenderer.GetGameObject();
    Assert.IsTrue(result == null);
    result = go.GetGameObject();
    Assert.IsTrue(result == null);

    result = ((GameObject)null).GetGameObject();
    Assert.IsTrue(result == null);

    result = ((SpriteRenderer)null).GetGameObject();
    Assert.IsTrue(result == null);
    yield break;
}

This test verifies:

  1. Normal operation with valid objects
  2. Behavior after component destruction (object still valid)
  3. Behavior after GameObject destruction (both references invalid)
  4. Explicit null input handling

Pattern: SerializedObject with Destroyed Target

Editor code often works with SerializedObject and SerializedProperty. When the target object is destroyed, these become invalid but may not be null.

[Test]
public void DrawerHandlesDestroyedSerializedObjectTarget()
{
    MyScriptableObject target = CreateScriptableObject<MyScriptableObject>();
    SerializedObject serializedObject = new SerializedObject(target);
    SerializedProperty property = serializedObject.FindProperty("myField");

    Object.DestroyImmediate(target); // UNH-SUPPRESS: Test verifies behavior after target destroyed

    // SerializedObject.targetObject is now null
    Assert.DoesNotThrow(() => drawer.OnGUI(rect, property, label));
}

Real Example: ScriptableSingletonSerializationTests.cs

From /workspaces/com.wallstop-studios.unity-helpers/Tests/Editor/CustomDrawers/ScriptableSingletonSerializationTests.cs:

[Test]
public void IsScriptableSingletonTypeWithDestroyedObjectReturnsFalse()
{
    RegularScriptableObject target = CreateScriptableObject<RegularScriptableObject>();
    Object.DestroyImmediate(target); // UNH-SUPPRESS: Testing destroyed object handling

    // Unity's null check should handle destroyed objects
    bool result = SerializableDictionaryPropertyDrawer.IsScriptableSingletonType(target);
    Assert.IsFalse(result, "Destroyed object should return false (Unity null check).");
}

Real Example: WButtonRenderingTests.cs

From /workspaces/com.wallstop-studios.unity-helpers/Tests/Editor/Utils/WButton/WButtonRenderingTests.cs:

[Test]
public void NullEditorTargetHandledGracefully()
{
    RenderingTargetSingleButton asset = Track(
        ScriptableObject.CreateInstance<RenderingTargetSingleButton>()
    );
    UnityEditor.Editor editor = Track(UnityEditor.Editor.CreateEditor(asset));
    Dictionary<WButtonGroupKey, WButtonPaginationState> paginationStates = new();
    Dictionary<WButtonGroupKey, bool> foldoutStates = new();

    Object.DestroyImmediate(asset); // UNH-SUPPRESS: Test verifies behavior when target is destroyed
    _trackedObjects.Remove(asset);

    bool drawn = WButtonGUI.DrawButtons(
        editor,
        WButtonPlacement.Top,
        paginationStates,
        foldoutStates,
        UnityHelpersSettings.WButtonFoldoutBehavior.AlwaysOpen,
        triggeredContexts: null,
        globalPlacementIsTop: true
    );

    Assert.That(drawn, Is.False, "Should return false when target is destroyed");
}

Null References Where "Shouldn't Happen"

References that "can't be null" sometimes become null due to serialization issues, race conditions, improper initialization, or user error. Correct code must handle these cases gracefully.

Pattern: Explicit Null Input Handling

Test that methods handle null inputs gracefully, even when callers are "supposed to" provide non-null values.

[Test]
public void ProcessNullInputDoesNotThrow()
{
    Assert.DoesNotThrow(() => Processor.Process(null));
}

[Test]
public void ProcessNullInputReturnsDefault()
{
    var result = Processor.Process(null);
    Assert.AreEqual(default(MyType), result);
}

Real Example: ObjectHelperTests.cs

From /workspaces/com.wallstop-studios.unity-helpers/Tests/Runtime/Helper/ObjectHelperTests.cs:

[UnityTest]
public IEnumerator GetGameObject()
{
    GameObject go = Track(new GameObject("Test", typeof(SpriteRenderer)));
    SpriteRenderer spriteRenderer = go.GetComponent<SpriteRenderer>();

    // ... (normal operation tests) ...

    // Test explicit null input handling
    result = ((GameObject)null).GetGameObject();
    Assert.IsTrue(result == null);

    result = ((SpriteRenderer)null).GetGameObject();
    Assert.IsTrue(result == null);
    yield break;
}

This test verifies that extension methods handle explicit null inputs gracefully, returning null rather than throwing NullReferenceException.

Pattern: Null Serialized Property Handling

Editor code may receive null SerializedProperty references due to timing issues or invalid property paths.

[Test]
public void DrawPropertyHandlesNullProperty()
{
    Assert.DoesNotThrow(() => CustomDrawer.DrawProperty(null, GUIContent.none));
}

[Test]
public void GetValueFromNullPropertyReturnsDefault()
{
    object result = PropertyHelper.GetValue(null);
    Assert.IsNull(result);
}

Pattern: Null Collection Elements

Collections may contain null elements even when the code assumes they won't.

[Test]
public void ProcessCollectionWithNullElementsSucceeds()
{
    List<string> items = new() { "A", null, "B", null, "C" };

    Assert.DoesNotThrow(() => Processor.ProcessAll(items));
}

[Test]
public void FilterHandlesNullElements()
{
    List<Component> components = new() { validComponent, null, anotherValid };

    List<Component> filtered = ComponentFilter.FilterValid(components);

    Assert.That(filtered, Has.None.Null);
    Assert.AreEqual(2, filtered.Count);
}

Invalid Enum Values

Enums can hold any integer value their underlying type supports, not just defined members. This occurs when:

  • Deserializing data from older/newer versions
  • Casting user input or external data
  • Data corruption

Pattern: Cast Invalid Integer to Enum

[Test]
public void DisplayNameWithInvalidEnumValue()
{
    TestEnum invalidValue = (TestEnum)999;

    string displayName = invalidValue.ToDisplayName();

    Assert.IsNotEmpty(displayName, "Should return some string, not crash");
}

Pattern: Test All Enum Operations with Invalid Values

[Test]
public void CachedNameWithInvalidEnumValue()
{
    TestEnum invalidValue = (TestEnum)999;

    string cachedName = invalidValue.ToCachedName();

    Assert.IsNotEmpty(cachedName);
}

[Test]
public void HasFlagNoAllocWithInvalidEnumValue()
{
    TestEnum invalidValue = (TestEnum)999;

    Assert.IsTrue(invalidValue.HasFlagNoAlloc(invalidValue));
    Assert.IsFalse(TestEnum.First.HasFlagNoAlloc(invalidValue));
}

Real Example: EnumExtensionTests.cs

From /workspaces/com.wallstop-studios.unity-helpers/Tests/Runtime/Extensions/EnumExtensionTests.cs:

[Test]
public void DisplayNameWithInvalidEnumValue()
{
    TestEnum invalidValue = (TestEnum)999;
    string displayName = invalidValue.ToDisplayName();
    Assert.IsNotEmpty(displayName);
}

[Test]
public void CachedNameWithInvalidEnumValue()
{
    TestEnum invalidValue = (TestEnum)999;
    string cachedName = invalidValue.ToCachedName();
    Assert.IsNotEmpty(cachedName);
}

[Test]
public void HasFlagNoAllocWithInvalidEnumValue()
{
    TestEnum invalidValue = (TestEnum)999;
    Assert.IsTrue(invalidValue.HasFlagNoAlloc(invalidValue));
    Assert.IsFalse(TestEnum.First.HasFlagNoAlloc(invalidValue));
}

Pattern: Invalid SerializationType

[Test]
public void GenericSerializeInvalidSerializationTypeThrowsException()
{
    TestMessage msg = new() { Id = 1, Name = "Test" };

    Assert.Throws<InvalidEnumArgumentException>(() =>
        Serializer.Serialize(msg, (SerializationType)999)
    );
}

[Test]
public void GenericDeserializeInvalidSerializationTypeThrowsException()
{
    byte[] data = { 1, 2, 3 };

    Assert.Throws<InvalidEnumArgumentException>(() =>
        Serializer.Deserialize<TestMessage>(data, (SerializationType)999)
    );
}

Pattern: Flags Enum with All Bits Set

[Test]
public void FlagsEnumShowsWhenAllFlagsSetAndExpectedIsSubset()
{
    OdinShowIfFlagsTarget target = CreateScriptableObject<OdinShowIfFlagsTarget>();
    target.flags = (TestFlagsEnum)(-1); // All bits set

    (bool success, bool shouldShow) = EvaluateCondition(
        target,
        nameof(OdinShowIfFlagsTarget.flags),
        new WShowIfAttribute(
            nameof(OdinShowIfFlagsTarget.flags),
            expectedValues: new object[] { TestFlagsEnum.FlagA | TestFlagsEnum.FlagB }
        )
    );

    Assert.That(success, Is.True);
    Assert.That(shouldShow, Is.True, "Field should show when all flags set and expected is subset");
}

Capacity claims without large test buffers

Keep hostile serialized capacity and index claims, including int.MaxValue, in correctness regressions. Configure a small SerializationCapacityLimits.MaximumRestoredCapacity before decoding a capacity hint, assert the restored capacity exactly, and restore the setting in teardown. The same payload must clamp at a low limit and retain its claimed capacity after the test raises that limit. Default-limit values can be checked directly through Clamp and TryAccept without allocating their corresponding buffers.

This exercises rejection, clamping, growth, and limit configuration while keeping routine tests small. Reserve large real buffers for separately categorized stress or performance tests. These bounded fixtures reduce test memory pressure; passing them alone does not establish the cause of an editor termination.

Overflow Conditions

Test behavior at the boundaries of numeric types to catch overflow, underflow, and precision issues.

Pattern: Extreme Numeric Values

[Test]
public void BinaryRoundTripComplexObjectAllFieldsCorrect()
{
    ComplexMessage msg = new()
    {
        Integer = int.MaxValue,
        Double = Math.PI,
        Text = "Complex test with unicode",
        Data = new byte[] { 1, 2, 3, 255, 0, 128 },
    };

    byte[] serialized = Serializer.BinarySerialize(msg);
    ComplexMessage deserialized = Serializer.BinaryDeserialize<ComplexMessage>(serialized);

    Assert.AreEqual(msg.Integer, deserialized.Integer);
    Assert.AreEqual(msg.Double, deserialized.Double);
}

Pattern: Edge Case Values via TestCaseSource

private static IEnumerable<TestCaseData> EdgeCaseTestData()
{
    yield return new TestCaseData(new[] { int.MaxValue }, int.MaxValue)
        .SetName("Input.MaxValue.HandlesCorrectly");
    yield return new TestCaseData(new[] { int.MinValue }, int.MinValue)
        .SetName("Input.MinValue.HandlesCorrectly");
    yield return new TestCaseData(new[] { 0 }, 0)
        .SetName("Input.Zero.ReturnsZero");
    yield return new TestCaseData(new[] { -1 }, -1)
        .SetName("Input.Negative.HandlesCorrectly");
}

[Test]
[TestCaseSource(nameof(EdgeCaseTestData))]
public void ProcessHandlesEdgeCases(int[] input, int expected)
{
    int result = MyProcessor.Process(input);

    Assert.AreEqual(expected, result);
}

Real Example: SerializerAdditionalTests.cs

From /workspaces/com.wallstop-studios.unity-helpers/Tests/Runtime/Serialization/SerializerAdditionalTests.cs:

[Test]
public void GenericSerializeWithAllTypesEdgeCaseData()
{
    ComplexMessage msg = new()
    {
        Integer = int.MinValue,
        Double = double.MaxValue,
        Text = string.Empty,
        Data = new byte[] { 0, 255 },
        StringList = new List<string> { "", "test" },
        Dictionary = new Dictionary<string, int> { [""] = 0, ["test"] = -1 },
    };

    foreach (SerializationType type in new[]
    {
        SerializationType.SystemBinary,
        SerializationType.Protobuf,
    })
    {
        byte[] serialized = Serializer.Serialize(msg, type);
        ComplexMessage deserialized = Serializer.Deserialize<ComplexMessage>(serialized, type);

        Assert.AreEqual(msg.Integer, deserialized.Integer, $"Failed for {type}");
        Assert.AreEqual(msg.Double, deserialized.Double, $"Failed for {type}");
    }
}

Corrupted Serialization State

Test handling of malformed, truncated, or invalid serialized data.

Pattern: Empty Data

[Test]
public void BinaryDeserializeEmptyArrayThrowsException()
{
    byte[] emptyData = Array.Empty<byte>();

    Assert.Throws<SerializationException>(() =>
        Serializer.BinaryDeserialize<TestMessage>(emptyData)
    );
}

[Test]
public void ProtoDeserializeEmptyArrayReturnsDefaultInstance()
{
    byte[] emptyData = Array.Empty<byte>();

    TestMessage result = Serializer.ProtoDeserialize<TestMessage>(emptyData);

    Assert.NotNull(result);
    Assert.AreEqual(0, result.Id);
}

Pattern: Corrupted Data

[Test]
public void BinaryDeserializeCorruptedDataThrowsException()
{
    byte[] corruptedData = { 0xFF, 0xFF, 0xFF, 0xFF };

    Assert.Throws<SerializationException>(() =>
        Serializer.BinaryDeserialize<TestMessage>(corruptedData)
    );
}

[Test]
public void FileIOReadFromInvalidJsonThrowsException()
{
    string filePath = Path.Combine(_tempDirectory, "invalid.json");
    File.WriteAllText(filePath, "{ invalid json content }");

    Assert.Throws<JsonException>(() =>
        Serializer.ReadFromJsonFile<TestMessage>(filePath)
    );
}

Pattern: Null Data

[Test]
public void ProtoDeserializeNullDataThrowsException()
{
    Assert.Throws<ProtoException>(() =>
        Serializer.ProtoDeserialize<TestMessage>(null)
    );
}

[Test]
public void ProtoDeserializeWithTypeNullDataThrowsException()
{
    Assert.Throws<ArgumentException>(() =>
        Serializer.ProtoDeserialize<object>(null, typeof(TestMessage))
    );
}

Concurrent Access Edge Cases

Multi-threaded code can encounter states that are impossible in single-threaded execution. Unity Helpers uses #if !SINGLE_THREADED conditionals to wrap concurrent tests.

Pattern: Concurrent Operations Do Not Corrupt State

#if !SINGLE_THREADED
[Test]
public void ConcurrentSetsDoNotCorruptCache()
{
    using Cache<int, int> cache = CacheBuilder<int, int>
        .NewBuilder()
        .MaximumSize(1000)
        .Build();

    int threadCount = 4;
    int operationsPerThread = 250;
    CountdownEvent countdownEvent = new(threadCount);
    Exception capturedException = null;

    for (int t = 0; t < threadCount; t++)
    {
        int threadIndex = t;
        ThreadPool.QueueUserWorkItem(_ =>
        {
            try
            {
                for (int i = 0; i < operationsPerThread; i++)
                {
                    int key = threadIndex * operationsPerThread + i;
                    cache.Set(key, key);
                }
            }
            catch (Exception ex)
            {
                capturedException = ex;
            }
            finally
            {
                countdownEvent.Signal();
            }
        });
    }

    countdownEvent.Wait(TimeSpan.FromSeconds(10));

    Assert.IsTrue(capturedException == null, $"Exception during concurrent sets: {capturedException}");
    Assert.AreEqual(threadCount * operationsPerThread, cache.Count);
}
#endif

Pattern: Mixed Read/Write Operations

From /workspaces/com.wallstop-studios.unity-helpers/Tests/Runtime/DataStructures/CacheTests.cs:

#if !SINGLE_THREADED
[Test]
public void ConcurrentSetsAndGetsDoNotCorruptCache()
{
    using Cache<int, int> cache = CacheBuilder<int, int>
        .NewBuilder()
        .MaximumSize(500)
        .Build();

    int threadCount = 4;
    int operationsPerThread = 500;
    CountdownEvent countdownEvent = new(threadCount);
    Exception capturedException = null;

    for (int t = 0; t < threadCount; t++)
    {
        int threadIndex = t;
        ThreadPool.QueueUserWorkItem(_ =>
        {
            try
            {
                for (int i = 0; i < operationsPerThread; i++)
                {
                    if (i % 2 == 0)
                    {
                        int key = threadIndex * 100 + (i % 100);
                        cache.Set(key, key);
                    }
                    else
                    {
                        int key = (threadIndex + 1) % threadCount * 100 + (i % 100);
                        cache.TryGet(key, out _);
                    }
                }
            }
            catch (Exception ex)
            {
                capturedException = ex;
            }
            finally
            {
                countdownEvent.Signal();
            }
        });
    }

    countdownEvent.Wait(TimeSpan.FromSeconds(10));

    Assert.IsNull(capturedException, $"Exception during concurrent operations: {capturedException}");
}
#endif

Pattern: Rapid Allocation/Deallocation

From /workspaces/com.wallstop-studios.unity-helpers/Tests/Runtime/Utils/BuffersTests.cs:

#if !SINGLE_THREADED
[Test]
public void WallstopFastArrayPoolConcurrentAccessRapidAllocationDeallocation()
{
    const int iterations = 1000;
    const int threadCount = 4;

    CountdownEvent countdownEvent = new(threadCount);
    Exception capturedException = null;

    for (int t = 0; t < threadCount; t++)
    {
        ThreadPool.QueueUserWorkItem(_ =>
        {
            try
            {
                for (int i = 0; i < iterations; i++)
                {
                    using (PooledArray<int> pooled = WallstopFastArrayPool<int>.Get(64, out _))
                    {
                        // Rapid acquire/release cycle
                    }
                }
            }
            catch (Exception ex)
            {
                capturedException = ex;
            }
            finally
            {
                countdownEvent.Signal();
            }
        });
    }

    countdownEvent.Wait(TimeSpan.FromSeconds(30));
    Assert.IsNull(capturedException, $"Exception during rapid allocation: {capturedException}");
}
#endif

Key Practices for Concurrent Tests

  1. Use CountdownEvent to synchronize thread completion
  2. Capture exceptions in threads since NUnit cannot catch them directly
  3. Use reasonable timeouts (10-30 seconds) to prevent test hangs
  4. Wrap in #if !SINGLE_THREADED for WebGL/IL2CPP compatibility
  5. Test both success and exception cases for thread safety

Invalid State Combinations

Some states are logically impossible during normal execution but can occur due to reflection, serialization bugs, or corrupted data.

Pattern: Empty Collections Where Non-Empty Expected

[Test]
public void ProcessEmptyArrayGracefully()
{
    int[] emptyArray = Array.Empty<int>();

    // Methods that "shouldn't" receive empty arrays should handle them
    int result = collection.Min(emptyArray);

    Assert.AreEqual(default(int), result);
}

[Test]
public void SortEmptyCollection()
{
    List<int> emptyList = new();

    Assert.DoesNotThrow(() => emptyList.Sort(SortAlgorithm.Tim));
    Assert.AreEqual(0, emptyList.Count);
}

Real Example: Spatial Tree with Zero Elements

From /workspaces/com.wallstop-studios.unity-helpers/Tests/Runtime/DataStructures/QuadTree2DTests.cs:

[Test]
public void ConstructorWithEmptyCollectionSucceeds()
{
    List<Vector2> points = new();
    QuadTree2D<Vector2> tree = CreateTree(points);
    Assert.IsNotNull(tree);

    List<Vector2> results = new();
    tree.GetElementsInRange(Vector2.zero, 10000f, results);
    Assert.AreEqual(0, results.Count);
}

[Test]
public void GetApproximateNearestNeighborsWithEmptyTreeReturnsEmpty()
{
    List<Vector2> points = new();
    QuadTree2D<Vector2> tree = CreateTree(points);
    List<Vector2> results = new();

    tree.GetApproximateNearestNeighbors(Vector2.zero, 5, results);
    Assert.AreEqual(0, results.Count);
}

Pattern: Invalid Index/Key Access

[Test]
public void IndexerThrowsOnInvalidIndex()
{
    CyclicBuffer<int> buffer = new(5) { 1, 2 };

    Assert.Throws<IndexOutOfRangeException>(() => { _ = buffer[-1]; });
    Assert.Throws<IndexOutOfRangeException>(() => { _ = buffer[2]; });
    Assert.Throws<IndexOutOfRangeException>(() => { _ = buffer[int.MaxValue]; });
    Assert.Throws<IndexOutOfRangeException>(() => { _ = buffer[int.MinValue]; });
}

Real Example: CyclicBufferTests.cs

From /workspaces/com.wallstop-studios.unity-helpers/Tests/Runtime/DataStructures/CyclicBufferTests.cs:

[Test]
public void IndexerGetOutOfBounds()
{
    CyclicBuffer<int> buffer = new(5) { 1, 2 };

    Assert.Throws<IndexOutOfRangeException>(() =>
    {
        _ = buffer[-1];
    });
    Assert.Throws<IndexOutOfRangeException>(() =>
    {
        _ = buffer[2];
    });
    Assert.Throws<IndexOutOfRangeException>(() =>
    {
        _ = buffer[5];
    });
    Assert.Throws<IndexOutOfRangeException>(() =>
    {
        _ = buffer[int.MaxValue];
    });
    Assert.Throws<IndexOutOfRangeException>(() =>
    {
        _ = buffer[int.MinValue];
    });
}

Pattern: Disposed Object Access

[Test]
public void AccessAfterDisposeThrows()
{
    Cache<int, int> cache = CacheBuilder<int, int>
        .NewBuilder()
        .MaximumSize(100)
        .Build();

    cache.Dispose();

    Assert.Throws<ObjectDisposedException>(() => cache.Set(1, 1));
    Assert.Throws<ObjectDisposedException>(() => cache.TryGet(1, out _));
}

Pattern: Extreme Capacity Values

[Test]
public void IntMaxCapacityOk()
{
    CyclicBuffer<int> buffer = new(int.MaxValue);
    CollectionAssert.AreEquivalent(Array.Empty<int>(), buffer);

    const int tries = 50;
    List<int> expected = new(tries);
    for (int i = 0; i < tries; ++i)
    {
        buffer.Add(i);
        expected.Add(i);
        CollectionAssert.AreEquivalent(expected, buffer);
    }
}

Best Practices

Identifying "Impossible" States to Test

  1. Review defensive code paths: Any if (x == null) or try-catch suggests a potential "impossible" state
  2. Examine switch statements: Missing default cases indicate unhandled enum values
  3. Check serialization boundaries: Data crossing process/version boundaries can be corrupted
  4. Consider Unity lifecycle: Objects can be destroyed at any frame
  5. Look for race conditions: Multi-threaded code has timing-dependent states

Test Structure

Always include these categories in your tests:

Category Examples
Normal cases Typical usage, common inputs
Edge cases Empty, single element, boundary values
Negative cases Invalid inputs, error conditions
Extreme cases Maximum values, large collections
"The Impossible" Destroyed objects, invalid enums, corrupted data

UNH-SUPPRESS Usage

When testing destroyed object behavior, use the // UNH-SUPPRESS comment:

// UNH-SUPPRESS tells the test linter this DestroyImmediate is intentional
Object.DestroyImmediate(target); // UNH-SUPPRESS: Test verifies behavior after destruction

Only use this for intentional destruction testing, not for cleanup. Use Track() for normal test cleanup.

Assertions for "Impossible" States

Choose assertions based on expected behavior:

// When graceful handling is expected
Assert.DoesNotThrow(() => Process(invalidInput));
Assert.IsNotEmpty(invalidValue.ToDisplayName());
Assert.IsTrue(result == null);

// When exceptions are expected
Assert.Throws<InvalidEnumArgumentException>(() => Serialize(msg, (SerializationType)999));
Assert.Throws<SerializationException>(() => Deserialize(corruptedData));

// When default values are expected
Assert.AreEqual(default(T), result);
Assert.AreEqual(0, deserializedFromEmpty.Id);

Repeated primitive comparisons

For exhaustive bit or scalar checks, compare every value directly and call Assert.Fail on a mismatch. Keep the complete input matrix and final size or aggregate assertions. This avoids allocating NUnit constraints and formatting messages for each successful comparison. Check the failure paths with changed result and snapshot values before accepting a timing improvement.

Data-Driven Testing for Edge Cases

Use [TestCaseSource] to systematically cover impossible states:

private static IEnumerable<TestCaseData> ImpossibleStateTestCases()
{
    // Destroyed references
    yield return new TestCaseData(CreateDestroyedObject())
        .SetName("State.DestroyedObject.HandledGracefully");

    // Invalid enums
    yield return new TestCaseData((MyEnum)(-1))
        .SetName("State.NegativeEnumValue.HandledGracefully");
    yield return new TestCaseData((MyEnum)999)
        .SetName("State.LargeEnumValue.HandledGracefully");
    yield return new TestCaseData((MyEnum)int.MaxValue)
        .SetName("State.MaxIntEnumValue.HandledGracefully");

    // Overflow values
    yield return new TestCaseData(int.MaxValue)
        .SetName("State.IntMaxValue.HandledGracefully");
    yield return new TestCaseData(int.MinValue)
        .SetName("State.IntMinValue.HandledGracefully");

    // Corrupted strings
    yield return new TestCaseData("\0\0\0")
        .SetName("State.NullChars.HandledGracefully");
    yield return new TestCaseData(new string('\uD800', 1000))
        .SetName("State.InvalidSurrogates.HandledGracefully");
}

[Test]
[TestCaseSource(nameof(ImpossibleStateTestCases))]
public void ProcessHandlesImpossibleStates(object input)
{
    Assert.DoesNotThrow(() => Process(input));
}

Summary

Testing "impossible" states is essential for dependable production code. These tests:

  1. Catch silent failures before they reach users
  2. Document expected behavior for edge cases
  3. Prevent regressions when code is refactored
  4. Build confidence that defensive code works

When adding new features, always ask: "What happens if this input is destroyed, null, invalid, or corrupted?" Then write tests to answer that question.

For more information on contributing to Unity Helpers, see the Contributing guide.

📚 Documentation

Getting Started

Inspector Features

Effects System

Relational Components

Serialization

Spatial Trees

Logging

Utilities

Editor Tools

Guides

Performance

Project

Clone this wiki locally