Hello. Tell me, who knows how to add a unit test, written on with # to the project unit in the Editor tests runner?
- Tests in Unity are done somehow - eastwing
1 answer
In general, everything is simple.
Suppose there is a class
public class MyTestClass { public int HP = 100; public void DecreaseHP(int value) { HP -= value; } } In the Assets folder, create an Editor folder (if you don’t have one yet). All files with tests should be located in the Editor folder, or in its sub-directories.
To create a test file on the Editor folder, press the RMB and select either Create → C# Script (long path) or Create → Editor Test C# Script
If you add the script to the second option, Unity will generate the class as it should be. If not, you need to know that
- need to connect namespace for tests
using NUnit.Framework; - All test methods must be marked with the attribute
[Test]
You can also specify test attributes for the class, for example [TestFixture] , but this depends on ...
So, the minimum class for the test looks like this:
using UnityEngine; using NUnit.Framework; public class NewEditorTest { [Test] public void SomeMethod() { } } In principle, this is enough for him to appear in the Unit Test Runner . Click Window → Unit Test Runner and watch. ¯ \ _ (ツ) _ / ¯
The test looks like this:
// Имя метода желательно чтоб отражало, что проверяем, и каков результат ожидаем public void DecreaseHP_DescriptionOfWhatMethodWhouldDo() { var myTestClass = new MyTestClass(); myTestClass.HP = 10; myTestClass.DecreaseHP(2); // проверяем, что после манипуляций у нас значения совпадают Assert.AreEqual(8, myTestClass.HP); }