Code360 powered by Coding Ninjas X Code360 powered by Coding Ninjas X
Table of contents
Introduction 🤝
Unit Testing 🚀
Test Runner API 
Split Build And Run 💨
Build 🏗️
Run 🏃
Launching Specific Tests From Menu Item
Running Tests Before The Build
Frequently Asked Questions
How can we add a Particle System to an Object?
What are modules?
What does a Gravity Modifier do in a Particle System?
Last Updated: Mar 27, 2024

Testing in Unity

Master Python: Predicting weather forecasts
Ashwin Goyal
Product Manager @

Introduction 🤝

Testing your code to check if it works in accordance with your needs is a vital step in any development process, before moving to the next stage. In Unity, testing is done with the help of Unity Test Framework (UTF). The UTF allows Unity users to test their code on both Edit and Play Mode, as well as on target platforms including Standalone, Android, iOS, and others. UTF integrates the NUnit library, an open-source unit testing library for.Net languages, into Unity.

Testing in Unity

Unit Testing 🚀

A unit test is used to test a single "unit" of code. The specific definition of a "unit" varies, but the crucial thing to remember is that a unit test should only test one "module" at a time. A unit test should be written to ensure that a short, logical bit of code operates precisely as expected in a given circumstance. 

Unit testing attempts to address code regressions by focusing on creating tests at the most granular level. The goal is to divide your software into logical little units and test each one independently to ensure that at least this portion of your project is sound.

Unit testing

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job

Test Runner API 

The Test Runner API allows you to run your tests programmatically from any script and receive a list of tests that will run in Edit Mode, Play Mode, or both without running them. You can hook into certain register/unregister callbacks at the beginning and end of each test, as well as at each level of the testing cycle, i.e. on the entire test assembly, each individual test fixture, and each test class and test.

You are given information about the test route that is about to be conducted at the start of each test. When the test is finished, the results are shown. A new customisation point allows you to run the UTF on target devices in addition to running it in Play Mode in the Unity Editor. Before you create the Player, you may edit the Player build options, such as changing the test run settings and specifying the build locations.

void Execute(ExecutionSettings executionSettings);
void RegisterCallbacks<T>(T testCallbacks, int priority = 0) where T : ICallbacks;
void UnregisterCallbacks<T>(T testCallbacks) where T : ICallbacks;
void RetrieveTestList(TestMode testMode, Action<ITestAdaptor> callback);

Split Build And Run 💨

Splitting the build and run processes is handy when you wish to execute tests on a target device that is not connected to your local workstation, such as a cloud device (or is multiple devices in the cloud). To do so, you must first modify the test Player build procedure by performing the following actions:

1. Disable AutoRun so that the Player does not launch and perform the tests once you create it.

2. Instead of saving it to the system's temporary folder (where it would be kept by default), save it to a known place.

Then, on the Player side, you add custom result reporting (through the callback method) to capture all the results and export them to an XML file, or whatever format works best for your project. The following examples illustrate splitting build and run for an application:

Build 🏗️

public class SetupPlaymodeTestPlayer : ITestPlayerBuildModifier {
   public BuildPlayerOptions ModifyOptions(BuildPlayerOptions playerOptions) {
    playerOptions.options &= ~(BuildOptions.AutoRunPlayer | BuildOptions.ConnectToHost);
    var buildLocation = Path.GetFullPath("TestPlayers");
    var fileName = Path.GetFileName(playerOptions.locationPathName);
    if (!string.IsNullOrEmpty(fileName))
        buildLocation = Path.Combine(buildLocation, fileName);
    playerOptions.locationPathName = buildLocation;
    return playerOptions;


Run 🏃

Run Unity tests

[assembly: TestRunCallback(typeof (ResultSerializer))]
public class ResultSerializer: ITestRunCallback {
 public void RunStarted(ITest testsToRun) {}
 public void TestStarted(ITest test) {}
 public void TestFinished(ITestResult result) {}
 public void RunFinished(ITestResult testResults) {
   var route = Path.Combine(Application.persistentDataPath, "testresults.xml");
   using(var xw = XmlWriter.Create(route, new XmlWriterSettings {
     Indent = true
   System.Console.WriteLine($"***\n\nTEST RESULTS WRITTEN TO\n\n\t{route}\n\n***");
   Application.Quit(testResults.FailCount > 0 ? 1 : 0);

Launching Specific Tests From Menu Item

Instead of a Console Window, we can receive validation results in a test suite with clear signs in a dedicated place in the Editor. We can accomplish this by running specific tests for each menu item.

🔥 We begin with a method that is hooked to a MenuItem in the same manner as any other Editor extension menu item. After that, the method constructs a ScriptableObject callback object. 

🔥 Instead of a standard class, you use a ScriptableObject so that the tests can do things like cause a domain reload while keeping your callbacks untouched. When the ScriptableObject is set, it registers for callbacks. When it is disabled, it unregisters. 

🔥 Then we create filters. When you run a test for a MenuItem, you frequently want to run tests for a specified category or group. Asynchronous test execution is possible using filters. 

🔥 It will run over numerous frames, enabling you to have UnityTest, UnitySetUp, and UnityTearDown tick the engine loop while the test is running. When the test completes and registers RunFinished, you may configure it to show a message or open a results window, depending on your workflow. The following code example illustrates this:

public class RunTestsFromMenu: ScriptableObject, ICallbacks {
   /*create an instance*/
   [MenuItem(“Tools / Running useful tests”)] public static void DoRunTests() {
     CreateInstance < RunTestsFromMenu > ().StartTestRun();
   /*starts test run*/
   private void StartTestRun() {
     hideFlags = HideFlags.HideAndDontSave;
     CreateInstance < TestRunnerApi > ().Execute(new ExecutionSettings {
       filters = new [] {
         new Filter {
           categoryNames = new [] {
   /* ...RunStarted, TestStarted, TestFinished... */
   public void OnEnable() {
     CreateInstance < TestRunnerApi > ().RegisterCallbacks(this);
   public void OnDisable() {
     CreateInstance < TestRunnerApi > ().UnregisterCallbacks(this);
   public void RunFinished(ITestResultAdaptor result) {

Running Tests Before The Build

Running tests before the build can be difficult since the build process needs the tests to be run from a callback, which means there is no time to pump the engine update loop. However, the advantage is that you can test that basic functionality works before investing effort in creating.

🔥 This application may be built using the IPreprocessBuildWithReport interface, just like any other type of build preprocessing. To obtain the results, simply register a callback as normal.

🔥 Since you can't enter Play Mode during a build, you may utilise the Test Runner API to run particular tests in Edit Mode. You may filter for those tests by category, such as a pre-build validation test category. These tests can be run concurrently.

🔥 Examine the results once the test is done. If something goes wrong, you may throw a BuildFailed exception, which will cause the build to fail.

public ITestResultAdaptor Result { get; private set; }     
   public void RunStarted(ITestAdaptor testsToRun) { }
   public void TestStarted(ITestAdaptor test) { }
   public void TestFinished(ITestResultAdaptor result) { }
   public void RunFinished(ITestResultAdaptor result)
    Result = result;

Must Read Sanity Testing vs Smoke Testing

Frequently Asked Questions


How can we add a Particle System to an Object?

Select GameObject > Effects > Particle System from the top menu dropdown.

What are modules?

The particle system Component contains numerous subsections, each of these subsections is referred to as a Module. These Modules include the particle system's settings.

What does a Gravity Modifier do in a Particle System?

It scales the Gravity value set in the Physics Manager window of Unity. If it is set to O, gravity will be disabled.


In this blog, we discussed the Unit Testing, testing process in unity through Unity Test Framework, running test cases before the build and throwing error exceptions on failing of the test cases.
Cheers, you have reached the end. Hope you liked the blog and it has added some knowledge to your life. Please look at these similar topics to learn more:

🔥 Adding Script to Unity 

🔥 Installing Unity

🔥 Unity Console

🔥 Unity 3D Canvas.

Refer to our Coding Ninjas Studio Guided Path to learn Data Structures and Algorithms, Competitive Programming, JavaScript, System Design, and even more! You can also check out the mock test series and participate in the contests hosted by Coding Ninjas Studio! But say you're just starting and want to learn about questions posed by tech titans like Amazon, Microsoft, Uber, and so on. In such a case, for placement preparations, you can also look at the problemsinterview experiences, and interview bundle.

You should also consider our premium courses to offer your career advantage over others!

Please upvote our blogs if you find them useful and exciting!

Thank you

Happy Coding!

Previous article
Audio in Unity
Next article
Oracle Certified Associate, Java SE 8 Programmer
Live masterclass