创建一个空的项目
在Assets下创建一个空的文件夹Editor(Create->Folder)
在Editor下创建一个Tests Assembly Floder 并重命名为MyTest
然后在MyTest下创建一个C# Test Script并重命名为MyTest
将下面的代码复制进MyTest中
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
using MyGame;
namespace Tests
{
public class MyTest
{
private Calculator calc;
// A Test behaves as an ordinary method
[Test]
public void MyTest_base()
{
Assert.AreEqual(55,
calc.Sum(1,10));
// Use the Assert class to test conditions
}
[Test]
public void MyTest_02_ad()
{
Assert.AreEqual(2500,
calc.Sum(1, 100,2));
// Use the Assert class to test conditions
}
[Test]
public void MyTest_03_sp()
{
Assert.AreEqual(5050,
calc.Sum(100, 1, -1));
// Use the Assert class to test conditions
}
[SetUp]
public void SetUp()
{
calc = new Calculator();
}
[TearDown]
public void TearDown()
{
//todo
}
}
}
保存回到Unity中,在Asset下再创建一个Tests Assembly Floder 并重命名为MyGame
然后在MyGame下创建一个C# Sprite并重命名为Calculator
打开Calculator并将下面的代码复制进去
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace MyGame
{
public class Calculator
{
public int Sum(int start, int end, int step = 1)
{
int sum = 0;
for (int i = start; i <= end; i += step)
{
sum += i;
}
return sum;
//return 0;
}
}
}
在Inspector中,添加Assembly Definition Reference并设置为MyGame
然后拉到最下面点击Apply(或者Unity弹出窗口时点击Apply)
这样Unity的报错信息就会消失,代码中也不会显示错误了
最后打开Window->General中的Test Runner
选择PlayMod界面,然后点击Run All
即可完成测试,绿色标识为测试通过,红色标识为测试不通过
图中的测试结果为MyTest_03_sp不通过,即代码有误