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.
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.
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.
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 filenames; the inventory retains their original package-relative paths. 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.
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-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.
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.
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.
[Test]publicvoidGetGameObjectHandlesDestroyedComponent(){GameObjectgo=Track(newGameObject("Test",typeof(SpriteRenderer)));SpriteRendererspriteRenderer=go.GetComponent<SpriteRenderer>();Object.DestroyImmediate(spriteRenderer);// UNH-SUPPRESS: Test verifies behavior after component destructionGameObjectresult=spriteRenderer.GetGameObject();Assert.IsTrue(result==null,"Should return null for destroyed component");}
[Test]publicvoidGetCenterUsesCenterPointOffsetWhenAvailable(){GameObjectgo=Track(newGameObject("CenterPointTest",typeof(CenterPointOffset)));go.transform.position=newVector3(5f,5f,0f);CenterPointOffsetoffset=go.GetComponent<CenterPointOffset>();offset.offset=newVector2(3f,4f);Assert.AreEqual(offset.CenterPoint,go.GetCenter());Object.DestroyImmediate(offset);// UNH-SUPPRESS: Test verifies behavior after component destructionAssert.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.
[UnityTest]publicIEnumeratorGetGameObject(){GameObjectgo=Track(newGameObject("Test",typeof(SpriteRenderer)));SpriteRendererspriteRenderer=go.GetComponent<SpriteRenderer>();GameObjectresult=go.GetGameObject();Assert.AreEqual(result,go);result=spriteRenderer.GetGameObject();Assert.AreEqual(result,go);Object.DestroyImmediate(spriteRenderer);// UNH-SUPPRESS: Test verifies behavior after component destructionresult=spriteRenderer.GetGameObject();Assert.IsTrue(result==null);result=go.GetGameObject();Assert.AreEqual(result,go);Object.DestroyImmediate(go);// UNH-SUPPRESS: Test verifies behavior after GameObject destructionresult=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);yieldbreak;}
This test verifies:
Normal operation with valid objects
Behavior after component destruction (object still valid)
Behavior after GameObject destruction (both references invalid)
[Test]publicvoidDrawerHandlesDestroyedSerializedObjectTarget(){MyScriptableObjecttarget=CreateScriptableObject<MyScriptableObject>();SerializedObjectserializedObject=newSerializedObject(target);SerializedPropertyproperty=serializedObject.FindProperty("myField");Object.DestroyImmediate(target);// UNH-SUPPRESS: Test verifies behavior after target destroyed// SerializedObject.targetObject is now nullAssert.DoesNotThrow(()=>drawer.OnGUI(rect,property,label));}
Real Example: ScriptableSingletonSerializationTests.cs¶
From /workspaces/com.wallstop-studios.unity-helpers/Tests/Editor/CustomDrawers/ScriptableSingletonSerializationTests.cs:
[Test]publicvoidNullEditorTargetHandledGracefully(){RenderingTargetSingleButtonasset=Track(ScriptableObject.CreateInstance<RenderingTargetSingleButton>());UnityEditor.Editoreditor=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);booldrawn=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");}
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.
[Test]publicvoidDisplayNameWithInvalidEnumValue(){TestEnuminvalidValue=(TestEnum)999;stringdisplayName=invalidValue.ToDisplayName();Assert.IsNotEmpty(displayName,"Should return some string, not crash");}
Pattern: Test All Enum Operations with Invalid Values¶
[Test]publicvoidFlagsEnumShowsWhenAllFlagsSetAndExpectedIsSubset(){OdinShowIfFlagsTargettarget=CreateScriptableObject<OdinShowIfFlagsTarget>();target.flags=(TestFlagsEnum)(-1);// All bits set(boolsuccess,boolshouldShow)=EvaluateCondition(target,nameof(OdinShowIfFlagsTarget.flags),newWShowIfAttribute(nameof(OdinShowIfFlagsTarget.flags),expectedValues:newobject[]{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");}
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.
[Test]publicvoidBinaryRoundTripComplexObjectAllFieldsCorrect(){ComplexMessagemsg=new(){Integer=int.MaxValue,Double=Math.PI,Text="Complex test with unicode",Data=newbyte[]{1,2,3,255,0,128},};byte[]serialized=Serializer.BinarySerialize(msg);ComplexMessagedeserialized=Serializer.BinaryDeserialize<ComplexMessage>(serialized);Assert.AreEqual(msg.Integer,deserialized.Integer);Assert.AreEqual(msg.Double,deserialized.Double);}
[Test]publicvoidGenericSerializeWithAllTypesEdgeCaseData(){ComplexMessagemsg=new(){Integer=int.MinValue,Double=double.MaxValue,Text=string.Empty,Data=newbyte[]{0,255},StringList=newList<string>{"","test"},Dictionary=newDictionary<string,int>{[""]=0,["test"]=-1},};foreach(SerializationTypetypeinnew[]{SerializationType.SystemBinary,SerializationType.Protobuf,}){byte[]serialized=Serializer.Serialize(msg,type);ComplexMessagedeserialized=Serializer.Deserialize<ComplexMessage>(serialized,type);Assert.AreEqual(msg.Integer,deserialized.Integer,$"Failed for {type}");Assert.AreEqual(msg.Double,deserialized.Double,$"Failed for {type}");}}
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¶
[Test]publicvoidProcessEmptyArrayGracefully(){int[]emptyArray=Array.Empty<int>();// Methods that "shouldn't" receive empty arrays should handle themintresult=collection.Min(emptyArray);Assert.AreEqual(default(int),result);}[Test]publicvoidSortEmptyCollection(){List<int>emptyList=new();Assert.DoesNotThrow(()=>emptyList.Sort(SortAlgorithm.Tim));Assert.AreEqual(0,emptyList.Count);}
// UNH-SUPPRESS tells the test linter this DestroyImmediate is intentionalObject.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.
// When graceful handling is expectedAssert.DoesNotThrow(()=>Process(invalidInput));Assert.IsNotEmpty(invalidValue.ToDisplayName());Assert.IsTrue(result==null);// When exceptions are expectedAssert.Throws<InvalidEnumArgumentException>(()=>Serialize(msg,(SerializationType)999));Assert.Throws<SerializationException>(()=>Deserialize(corruptedData));// When default values are expectedAssert.AreEqual(default(T),result);Assert.AreEqual(0,deserializedFromEmpty.Id);
Testing "impossible" states is essential for dependable production code. These tests:
Catch silent failures before they reach users
Document expected behavior for edge cases
Prevent regressions when code is refactored
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.