9. Using the UnityTest Attribute
Use the [UnityTest] to write tests that run across multiple frames.
Read time 1 minuteLast updated 10 days ago
Learning objectives
This section will introduce you to the custom Attribute, which allows for creating tests that run over multiple frames.
[UnityTest]Intro and motivation
An important extension to the Nunit framework that we've made is introducing the attribute. The attribute allows for creating tests that can yield and resume running after a certain condition. Therefore the test must have the return type of . You can then yield back a yield instruction or null, like so:
[UnityTest]IEnumerator[UnityTest]public IEnumerator MyTest(){ DoSomething(); // Skip 1 frame. yield return null; DoSomethingElse();}
In the snippet above we call the method, then skip one frame before calling the method.
DoSomethingDoSomethingElseFor more information on the yield keyword in C#, see the Microsoft documentation.
Exercise
In the sample you will find a Play Mode test assembly set up with one Play Mode test in it. The PlayMode test does not have a body yet, but there is a function called which will set up a cube with some physics applied.
9_UnityTestAttributePrepareCube()The task is to initialize the cube and then verify that it has moved after one frame has passed.
Solution
The full solution is available in the sample.
9_UnityTestAttribute_Solution[UnityTest]public IEnumerator CubeMovesDown(){ var cubeUnderTest = PrepareCube(); var initialPosition = cubeUnderTest.transform.position; yield return null; Assert.That(cubeUnderTest.transform.position, Is.Not.EqualTo(initialPosition));}