### Unity Prebuild Setup and Post-Build Cleanup Example Source: https://github.com/ottantotto88/blastblock/blob/master/Library/PackageCache/com.unity.test-framework@1.1.16/Documentation~/reference-setup-and-cleanup.md This C# code demonstrates implementing the `IPrebuildSetup` interface within a Unity test fixture. The `Setup` method is executed before the build process, allowing for modifications to assets like texture importers. It includes conditional compilation for Unity Editor specific APIs. ```csharp using NUnit.Framework; using UnityEngine; [TestFixture] public class CreateSpriteTest : IPrebuildSetup { Texture2D m_Texture; Sprite m_Sprite; public void Setup() { #if UNITY_EDITOR var spritePath = "Assets/Resources/Circle.png"; var ti = UnityEditor.AssetImporter.GetAtPath(spritePath) as UnityEditor.TextureImporter; ti.textureCompression = UnityEditor.TextureImporterCompression.Uncompressed; ti.SaveAndReimport(); #endif } [SetUp] public void SetUpTest() { m_Texture = Resources.Load("Circle"); } [Test] public void WhenNullTextureIsPassed_CreateShouldReturnNullSprite() { // Check with Valid Texture. LogAssert.Expect(LogType.Log, "Circle Sprite Created"); Sprite.Create(m_Texture, new Rect(0, 0, m_Texture.width, m_Texture.height), new Vector2(0.5f, 0.5f)); Debug.Log("Circle Sprite Created"); // Check with NULL Texture. Should return NULL Sprite. m_Sprite = Sprite.Create(null, new Rect(0, 0, m_Texture.width, m_Texture.height), new Vector2(0.5f, 0.5f)); Assert.That(m_Sprite, Is.Null, "Sprite created with null texture should be null"); } } ``` -------------------------------- ### Running Unity Tests via Command Line Source: https://github.com/ottantotto88/blastblock/blob/master/Library/PackageCache/com.unity.test-framework@1.1.16/Documentation~/reference-command-line.md Execute Unity tests from the command line using specific arguments. This example demonstrates a basic setup for Windows. ```APIDOC ## POST /runTests ### Description Executes Unity tests from the command line. This command allows for automated testing and integration into CI/CD pipelines. ### Method POST ### Endpoint Unity.exe ### Parameters #### Path Parameters - **PATH_TO_YOUR_PROJECT** (string) - Required - The absolute or relative path to your Unity project directory. #### Query Parameters - **-runTests** (boolean) - Required - Initiates the test execution process. - **-batchmode** (boolean) - Required - Runs Unity in batch mode, suppressing all interactive dialogs and ensuring non-interactive execution. - **-testResults** (string) - Required - Specifies the file path where the test results XML file should be saved. Example: `C:\temp\results.xml`. - **-testPlatform** (string) - Optional - Defines the platform on which to run the tests. Supported values include `PS4`, `EditMode`, `PlayMode`, `StandaloneWindows`, `StandaloneWindows64`, `StandaloneLinux64`, `StandaloneOSX`, `iOS`, `Android`, `XboxOne`. Defaults to `EditMode` if not specified. - **-testCategory** (string) - Optional - A semicolon-separated list of test categories to include. Tests must belong to at least one specified category to be included. - **-testFilter** (string) - Optional - A semicolon-separated list of specific test names or a regular expression pattern to match tests by their full name. Used in conjunction with `testCategory` for more granular filtering. - **-assemblyNames** (string) - Optional - A semicolon-separated list of test assembly names to include in the test run. - **-playerHeartbeatTimeout** (integer) - Optional - The duration in seconds the editor waits for heartbeats after starting a test run on a player. Defaults to 600 seconds (10 minutes). - **-runSynchronously** (boolean) - Optional - If included, forces tests to run synchronously within a single editor update call. This is only supported for EditMode tests and will filter out tests that span multiple frames. - **-testSettingsFile** (string) - Optional - Path to a `TestSettings.json` file to configure advanced test run options. ### Request Example ```bash Unity.exe -runTests -batchmode -projectPath "C:\Projects\MyUnityProject" -testResults "C:\temp\results.xml" -testPlatform Android -testCategory "MyCategory" -testFilter "MyTestClass.MyTestMethod" ``` ### Response #### Success Response (200) - **message** (string) - Confirmation that the test run has been initiated. #### Response Example ```json { "message": "Test run initiated successfully. Results will be saved to C:\temp\results.xml." } ``` ``` -------------------------------- ### Setup and Cleanup with IPrebuildSetup and IPostBuildCleanup Source: https://github.com/ottantotto88/blastblock/blob/master/Library/PackageCache/com.unity.test-framework@1.1.16/Documentation~/TableOfContents.md Illustrates the use of `IPrebuildSetup` and `IPostBuildCleanup` interfaces for defining actions that run before and after a build process, respectively. These are valuable for preparing the project or cleaning up artifacts related to testing. ```csharp using UnityEditor.Build; using UnityEditor.Callbacks; public class MyBuildCallbacks : IPrebuildSetup, IPostBuildCleanup { public void OnPrebuildSetup(string artifactsPath) { // Code to run before the build UnityEngine.Debug.Log("Pre-build setup executed."); } public void OnPostBuildCleanup(string artifactsPath) { // Code to run after the build UnityEngine.Debug.Log("Post-build cleanup executed."); } } ``` -------------------------------- ### Configure Test Settings with JSON Source: https://github.com/ottantotto88/blastblock/blob/master/Library/PackageCache/com.unity.test-framework@1.1.16/Documentation~/reference-command-line.md Defines advanced test run configurations using a JSON file. This example shows settings for scripting backend and API profile. ```json { "scriptingBackend": 2, "Architecture": null, "apiProfile": 0 } ``` -------------------------------- ### Execute Tests Source: https://github.com/ottantotto88/blastblock/blob/master/Library/PackageCache/com.unity.test-framework@1.1.16/Documentation~/reference-test-runner-api.md Starts a test run with specified execution settings. ```APIDOC ## Execute Tests ### Description Starts a test run with a given set of [ExecutionSettings](./reference-execution-settings.md). ### Method `void Execute(ExecutionSettings executionSettings)` ### Endpoint N/A (Method call within code) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **executionSettings** (ExecutionSettings) - Required - The settings to use for test execution. ``` -------------------------------- ### UnitySetUp and UnityTearDown Attributes Source: https://github.com/ottantotto88/blastblock/blob/master/Library/PackageCache/com.unity.test-framework@1.1.16/Documentation~/TableOfContents.md Shows how to use `[UnitySetUp]` and `[UnityTearDown]` attributes for setting up preconditions and cleaning up after tests. These attributes allow for common setup and teardown logic to be applied across multiple tests within a class. ```csharp using NUnit.Framework; using UnityEngine; public class MyTestClass { private GameObject testObject; [UnitySetUp] public IEnumerator Setup() { testObject = new GameObject("TestObject"); yield return null; // Wait for one frame if needed } [UnityTest] public IEnumerator TestSomething() { Assert.IsNotNull(testObject); yield return null; } [UnityTearDown] public IEnumerator TearDown() { Object.Destroy(testObject); yield return null; } } ``` -------------------------------- ### UnitySetUp and UnityTearDown Example in C# Source: https://github.com/ottantotto88/blastblock/blob/master/Library/PackageCache/com.unity.test-framework@1.1.16/Documentation~/reference-actions-outside-tests.md Demonstrates the usage of UnitySetUp and UnityTearDown attributes in C# for setting up and tearing down test environments, including yielding instructions like EnterPlayMode and ExitPlayMode. These methods expect an IEnumerator return type. ```csharp public class SetUpTearDownExample { [UnitySetUp] public IEnumerator SetUp() { yield return new EnterPlayMode(); } [Test] public void MyTest() { Debug.Log("This runs inside playmode"); } [UnitySetUp] public IEnumerator TearDown() { yield return new ExitPlayMode(); } } ``` -------------------------------- ### C# Example: Using EnterPlayMode and ExitPlayMode in Unity Tests Source: https://github.com/ottantotto88/blastblock/blob/master/Library/PackageCache/com.unity.test-framework@1.1.16/Documentation~/reference-custom-yield-instructions.md This C# code snippet demonstrates how to use custom yield instructions, specifically EnterPlayMode and ExitPlayMode, within a Unity Edit Mode test. It sets up a VideoPlayer, enters Play Mode, asserts its state, exits Play Mode, and cleans up. This example requires the Unity Test Framework package. ```csharp using NUnit.Framework; using System.Collections; using UnityEngine; using UnityEngine.TestTools; using UnityEngine.Video; public class VideoPlayerEditModeTests { private VideoPlayer m_VideoPlayerPrefab; [UnityTest] public IEnumerator PlayOnAwakeDisabled_DoesntPlayWhenEnteringPlayMode() { var videoPlayer = PrefabUtility.InstantiatePrefab(m_VideoPlayerPrefab.GetComponent()) as VideoPlayer; videoPlayer.playOnAwake = false; yield return new EnterPlayMode(); var videoPlayerGO = GameObject.Find(m_VideoPlayerPrefab.name); Assert.IsFalse(videoPlayerGO.GetComponent().isPlaying); yield return new ExitPlayMode(); Object.DestroyImmediate(GameObject.Find(m_VideoPlayerPrefab.name)); } } ``` -------------------------------- ### Execute Tests with ExecutionSettings in C# Source: https://github.com/ottantotto88/blastblock/blob/master/Library/PackageCache/com.unity.test-framework@1.1.16/Documentation~/reference-test-runner-api.md Starts a test run using the TestRunnerApi with a specified set of ExecutionSettings. This method is crucial for initiating automated test execution. ```csharp void Execute(ExecutionSettings executionSettings) ``` -------------------------------- ### C# Example: Setting up ICallbacks Listener Source: https://github.com/ottantotto88/blastblock/blob/master/Library/PackageCache/com.unity.test-framework@1.1.16/Documentation~/reference-icallbacks.md This C# code demonstrates how to set up a listener using the ICallbacks interface to receive notifications during test runs. It shows the registration of a custom callback class and how to access test results, specifically the count of failed tests, upon run completion. ```csharp public void SetupListeners() { var api = ScriptableObject.CreateInstance(); api.RegisterCallbacks(new MyCallbacks()); } private class MyCallbacks : ICallbacks { public void RunStarted(ITestAdaptor testsToRun) { } public void RunFinished(ITestResultAdaptor result) { Debug.Log(string.Format("Run finished {0} test(s) failed.", result.FailCount)); } public void TestStarted(ITestAdaptor test) { } public void TestFinished(ITestResultAdaptor result) { } } ``` -------------------------------- ### Vector3EqualityComparer Usage with NUnit Source: https://github.com/ottantotto88/blastblock/blob/master/Library/PackageCache/com.unity.test-framework@1.1.16/Documentation~/reference-comparer-vector3.md Demonstrates how to use the Vector3EqualityComparer with NUnit tests to assert equality between two Vector3 objects. It shows examples of using both the default comparer instance and a comparer with a custom allowed error. ```csharp using NUnit.Framework; using UnityEngine; // Assuming Vector3EqualityComparer and Vector3 are defined elsewhere [TestFixture] public class Vector3Test { [Test] public void VerifyThat_TwoVector3ObjectsAreEqual() { // Custom error 10e-6f var actual = new Vector3(10e-8f, 10e-8f, 10e-8f); var expected = new Vector3(0f, 0f, 0f); var comparer = new Vector3EqualityComparer(10e-6f); Assert.That(actual, Is.EqualTo(expected).Using(comparer)); //Default error 0.0001f actual = new Vector3(0.01f, 0.01f, 0f); expected = new Vector3(0.01f, 0.01f, 0f); Assert.That(actual, Is.EqualTo(expected).Using(Vector3EqualityComparer.Instance)); } } ``` -------------------------------- ### RecompileScripts Constructor Example Source: https://github.com/ottantotto88/blastblock/blob/master/Library/PackageCache/com.unity.test-framework@1.1.16/Documentation~/reference-recompile-scripts.md Demonstrates the creation and usage of the RecompileScripts yield instruction within a Unity Edit Mode test setup. It includes writing a temporary script, refreshing the asset database, and yielding the RecompileScripts instruction to trigger recompilation. ```csharp using System.Collections; using UnityEditor.TestRunner.Test.UnityTestRunner; using UnityEngine; using System.IO; public class ExampleTest { [UnitySetUp] public IEnumerator SetUp() { using (var file = File.CreateText("Assets/temp/myScript.cs")) { file.Write("public class ATempClass { }"); } AssetDatabase.Refresh(); yield return new RecompileScripts(); } } ``` -------------------------------- ### IErrorCallbacks - OnError Source: https://github.com/ottantotto88/blastblock/blob/master/Library/PackageCache/com.unity.test-framework@1.1.16/Documentation~/reference-ierror-callbacks.md Callback invoked when a build error occurs or a prebuild setup fails. It provides a detailed error message. ```APIDOC ## void OnError(string message) ### Description This method is called when the test run fails due to a build error or any failure in the IPrebuildSetup. ### Method Callback (void) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (void) This method does not return a value. #### Response Example None ``` -------------------------------- ### Initialize TestRunnerApi in C# Source: https://github.com/ottantotto88/blastblock/blob/master/Library/PackageCache/com.unity.test-framework@1.1.16/Documentation~/reference-test-runner-api.md Initializes an instance of the TestRunnerApi, which is a ScriptableObject used for managing test execution. This is the starting point for interacting with the API programmatically. ```csharp var testRunnerApi = ScriptableObject.CreateInstance(); ``` -------------------------------- ### TestRunnerApi Initialization Source: https://github.com/ottantotto88/blastblock/blob/master/Library/PackageCache/com.unity.test-framework@1.1.16/Documentation~/reference-test-runner-api.md Demonstrates how to initialize the TestRunnerApi in C#. ```APIDOC ## TestRunnerApi Initialization ### Description Initializes an instance of the TestRunnerApi. ### Method `ScriptableObject.CreateInstance()` ### Request Example ```csharp var testRunnerApi = ScriptableObject.CreateInstance(); ``` ### Response #### Success Response (Instance) - **testRunnerApi** (TestRunnerApi) - An initialized instance of the TestRunnerApi. ``` -------------------------------- ### TestRunnerApi ExecutionSettings Source: https://github.com/ottantotto88/blastblock/blob/master/Library/PackageCache/com.unity.test-framework@1.1.16/Documentation~/TableOfContents.md Demonstrates how to configure test execution using `ExecutionSettings` with the `TestRunnerApi`. This allows fine-grained control over which tests are run, their order, and other runtime parameters. ```csharp using UnityEditor.TestRunner.Api; using UnityEngine; public class ExecutionSettingsExample { public static void RunWithSettings() { var testRunnerApi = new TestRunnerApi(); var settings = new ExecutionSettings { runSynchronously = false, filters = new [] { new TestRunnerFilter { category = "EditMode" } } }; testRunnerApi.Run(settings); } } ``` -------------------------------- ### UnityPlatform Attribute Example in C# Source: https://github.com/ottantotto88/blastblock/blob/master/Library/PackageCache/com.unity.test-framework@1.1.16/Documentation~/reference-attribute-unityplatform.md This C# code snippet demonstrates how to use the UnityPlatform attribute to specify that a test method should only run on the WindowsPlayer platform. It requires the UnityEngine, UnityEngine.TestTools, and NUnit.Framework namespaces. ```csharp using UnityEngine; using UnityEngine.TestTools; using NUnit.Framework; [TestFixture] public class TestClass { [Test] [UnityPlatform(RuntimePlatform.WindowsPlayer)] public void TestMethod() { Assert.AreEqual(Application.platform, RuntimePlatform.WindowsPlayer); } } ``` -------------------------------- ### ExecutionSettings Constructors Source: https://github.com/ottantotto88/blastblock/blob/master/Library/PackageCache/com.unity.test-framework@1.1.16/Documentation~/reference-execution-settings.md Details on how to instantiate the ExecutionSettings class. ```APIDOC ## Constructors ### `ExecutionSettings(Filter[] filtersToExecute)` #### Description Creates an instance with a given set of filters, if any. #### Method CONSTRUCTOR #### Parameters ##### Path Parameters None ##### Query Parameters None ##### Request Body * **filtersToExecute** (Filter[]) - Required - An array of filters to apply to the test execution. ``` -------------------------------- ### Basic Vector Operations in Unity.Mathematics (C#) Source: https://github.com/ottantotto88/blastblock/blob/master/Library/PackageCache/com.unity.mathematics@1.1.0/Documentation~/mathematics.md Demonstrates the usage of Unity.Mathematics for basic vector operations like normalization and dot product. It utilizes static imports for the `math` class and common vector types like `float3`. This example showcases the shader-like syntax and the ease of integrating mathematical operations within a C# project. ```C# using static Unity.Mathematics.math; namespace MyNamespace { using Unity.Mathematics; // ... var v1 = float3(1,2,3); var v2 = float3(4,5,6); v1 = normalize(v1); v2 = normalize(v2); var v3 = dot(v1, v2); // ... } ``` -------------------------------- ### Test Settings File Configuration Source: https://github.com/ottantotto88/blastblock/blob/master/Library/PackageCache/com.unity.test-framework@1.1.16/Documentation~/reference-command-line.md Configure advanced test run options using a `TestSettings.json` file. This allows for fine-grained control over aspects like the scripting backend and target architecture. ```APIDOC ## POST /runTests/settings ### Description Applies advanced configurations to a Unity test run via a `TestSettings.json` file. This file allows customization of scripting backend, API profiles, and platform-specific settings. ### Method POST ### Endpoint TestSettings.json (referenced by `-testSettingsFile` argument) ### Parameters #### Request Body - **scriptingBackend** (integer) - Optional - Specifies the scripting backend. Values: `0` (.Net 2.0), `1` (.Net 2.0 Subset), `2` (.Net 4.6), `3` (.Net Standard 2.0), `5` (.Net micro profile). - **apiProfile** (integer) - Optional - Sets the .Net compatibility level. Values: `1` (.Net 2.0), `2` (.Net 2.0 Subset), `3` (.Net 4.6), `5` (.Net micro profile), `6` (.Net Standard 2.0). - **appleEnableAutomaticSigning** (boolean) - Optional - Enables automatic signing for Apple devices. - **appleDeveloperTeamID** (string) - Optional - Sets the Team ID for Apple developer accounts. - **architecture** (integer) - Optional - Defines the target architecture for Android builds. Values: `0` (None), `1` (ARMv7), `2` (ARM64), `4` (X86), `4294967295` (All). - **iOSManualProvisioningProfileType** (integer) - Optional - Specifies the provisioning profile type for iOS. Values: `0` (Automatic), `1` (Development), `2` (Distribution). ### Request Example ```json { "scriptingBackend": 1, "architecture": 2, "apiProfile": 3 } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation that the test settings have been applied. #### Response Example ```json { "message": "Test settings applied successfully." } ``` ```