簡介編輯器
在 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看效果
所有經過測試。