C#单元测试 在unity中的使用简单介绍 基于unity 2018.3.8f1

   简介编辑器

  在 Unity 进行单元测试,提升代码质量。函数

  使用工具工具

  unity 2018.3.8f1单元测试

  visual studio for mac测试

  .net 4.xspa

  前置知识点介绍.net

  Assert断言机制:须要进行测试代码时,能够用断言捕捉咱们进行的假设。code

举个栗子:直接上代码 注意抛出的异常不该该被捕获,系统须要用异常指示断言失败对象

 1 using System.Collections;  2 using System.Collections.Generic;  3 using NUnit.Framework;//引用单元测试类库
 4 using UnityEngine;  5 
 6 //断言测试代码类
 7 public class NUnitTestSprites : MonoBehaviour  8 {  9     private void Start() 10  { 11         Assert.IsTrue(true);//当传入参数 不为true时 抛出异常 断言失败
12         Assert.IsFalse(true);//和上面的相反
13 
14         Assert.IsNull(new List<int> { 6, 6, 6 });//当传入的参数 不为null时 抛出异常 断言失败
15         Assert.IsNotNull(null);//和上面相反
16 
17         Assert.AreEqual("six", "six");//比较两个参数 用相等运算符 判断是否相等 不相等 抛出异常 断言失败
18         Assert.AreNotEqual("six", "6");//和上面相反
19 
20         GameObject go1 = new GameObject(); 21         GameObject go2 = go1; 22         Assert.AreSame(go1, go2);//比较两个参数 断定两个对象是否引用同一个对象 不相同 抛出异常 断言失败
23         Assert.AreNotSame(go1, new GameObject()); 24 
25         Assert.Equals(new object(), new Object());//断定两个对象是否相等
26         Assert.Fail();//直接使断言失败
27         Assert.Inconclusive();//没法验证的断言
28 
29  } 30 }

    开始使用blog

  当前版本unity 已经自带 Test Runner 点击Window ->General ->TestRunner 如图所示: 

 

  首先建立EditMode测试代码 新建Editor文件夹  建立TestScript脚本

  此时会赠送一些代码 稍稍改一下

using System.Collections; using System.Collections.Generic; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; namespace Tests { public class TestEditor { // A Test behaves as an ordinary method
 [Test] public void TestEditorSimplePasses() { // Use the Assert class to test conditions
            Assert.IsTrue(false); } // A UnityTest behaves like a coroutine in Play Mode. In Edit Mode you can use // `yield return null;` to skip a frame.
 [UnityTest] public IEnumerator TestEditorWithEnumeratorPasses() { // Use the Assert class to test conditions. // Use yield to skip a frame.
            yield return null; } } }

  其中[Test]标签的为普通函数,[UnityTest]标签的函数有跳过当前帧的功能 他们都会显示在Test Runner中

  点击Run All 看看效果 

  红色表示测试失败 绿色表示测试成功

  接下来准备编辑器外部脚本 先建立TestModel文件夹 在里面会自动生成TestModel程序集

  程序集默认参数以下 

  在此文件夹下面的测试代码都会属于TestModel程序集中,若是不勾选Test Assemblies,那么在发布的时候测试代码也会打进包中。此时咱们再以相同的方式建立测试脚本,对脚本,修改脚本内容。

using System.Collections; using System.Collections.Generic; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; namespace Tests { public class TestModel { // A Test behaves as an ordinary method
 [Test] public void TestModelSimplePasses() { // Use the Assert class to test conditions
            Assert.IsNull(null); } // A UnityTest behaves like a coroutine in Play Mode. In Edit Mode you can use // `yield return null;` to skip a frame.
 [UnityTest] public IEnumerator TestModelWithEnumeratorPasses() { // Use the Assert class to test conditions. // Use yield to skip a frame.
            yield return null; } } }

   回到Test Runner 面板,点击PlayMode,点击Run All看效果

  所有经过测试。

相关文章
相关标签/搜索