Unity3D Unit Test

原创
2018/03/23 22:25
阅读数 4.2K

编者注

由于接触一段时间的Unity,写些小脚本,运行起来就可以。但是,当编写底层服务或独立的C#特性内容,无法方法的单元测试,这导致代码质量较低,开发效率差。随即研究Unity3D中的单元测试。

网络资料

查询的一些资料

Nunit

Rider

由于编者一直使用IDEA,所以Unity程序均用Rider进行开发。Rider具有Unity3d的插件。

自动测试代码

在Rider目录中,右键Add能够看到两个重要的文件,TestFixturePlay Mode Test,由于在Unity3d环境中,则优先测试Play Mode Test

using System.Collections;
using NUnit.Framework;
using UnityEngine.TestTools;

namespace ScriptsTest.Utils.Concurrent
{
    public class PlayModeTest1
    {
        [Test]
        public void PlayModeTest1SimplePasses()
        {
            // Use the Assert class to test conditions.
            
        }

        // A UnityTest behaves like a coroutine in PlayMode
        // and allows you to yield null to skip a frame in EditMode
        [UnityTest]
        public IEnumerator PlayModeTest1WithEnueratorPasses()
        {
            // Use the Assert class to test conditions.
            // yield to skip a frame
            yield return null;
        }
    }
}

碰到问题

虽然成功创建了测试,但是在Rider中执行测试一直报Failed。这是由于NUnit不具有UnityTest,无法识别该内容。

解决Rider中单元测试

通过TestFixture或删除[UnityTest]内容,就能够在Rider中执行单元测试

using System;
using NUnit.Framework;

namespace ScriptsTest
{
    [TestFixture]
    public class HelloWorldTest
    {
        [Test]
        public void helloworld()
        {
            string print = "Hello World!";
            Console.WriteLine(print);
            
            Assert.AreEqual(print, "Hello World!");
        }
    }
}

规范

与Unity无关的代码,可以直接使用TestFixture进行单元测试。
与Unity有关的代码,需要独立目录在Unity Test Runner中进行测试。

Unity Test Runner

Unity Test Runner
Unity Test Runner在UnityEditor菜单栏Windows->Test Runner 备注:仅仅测试成功EditorMode

展开阅读全文
加载中
点击加入讨论🔥(3) 发布并加入讨论🔥
打赏
3 评论
0 收藏
0
分享
返回顶部
顶部