Testing in Unity

Sindhu Rathod
XRPractices
Published in
2 min readJan 23, 2020

We do wonder at times saying “Is there a necessity to write tests when the functionality works as expected”. Well, here’s a scenario that helps us to understand why we need to.

Imagine a project with many views changing its data multiple times. It is common that at some point in time we might lose control over data. We might even end up wasting lots of time just analyzing the breach rather than the time we took in implementing it.

One way to have this under our control is by writing tests. There are different types of tests like unit tests, integration tests, UI tests, etc.. All we need to ensure is that the test pyramid down below is followed.

Essentially,

More unit tests would result in less integration → less system tests → less UI tests → less manual tests thereby fewer efforts to manage code.

What is unit test?

well, a unit test is a unit test :P, what you do in a unit test is test a single unit of code; one thing at a time.

A unit test is designed to validate the small, logical, snippet of code performing exactly as expected in a specific scenario.

How does Unity do it?

Unity has integrated NUnit library, an open-source unit testing library for .Net languages. More information on Unity Test Framework is found here.

Let us start by creating

1.The sample application form here .

2. Setting up Unity TestRunner from here .

You can skip this if you know how to create a new project in unity and a test runner.

Edit Mode Tests:Once you have the Unity and Test Runner up and ready , you can go ahead and create a script Calculation.cs.

public  class Calculation : MonoBehaviour
{
public int Sum(int firstNumber, int secondNumber)
{
return firstNumber + secondNumber;
}

I have created a calculation script which has a method sum() which takes in two integer arguments and returns an integer.Lets create a test script for this class CalculationTest.cs under Edit mode tests.


[Test(Description = "This tests Sum of given numbers")]
public void shouldReturnSumOfNumbers()
{
Assert.AreEqual(30,_calculation.Sum(12,18));
}

Adding [Test] attribute to a method in a class makes the method callable from the NUnit test runner. Description which is optional is used to add more details about an attribute (Description = “ more details about the test”).

Go to your TestRunner and click on tab Run All, Voila…

Try changing the values , you will see that the tests pass or fail accordingly.

--

--

Sindhu Rathod
XRPractices

ThoughtWorker! Introverts soul trapped in extroverts body.