LoginSignup
2
2

More than 5 years have passed since last update.

EditorModeのTestRunnerで非同期関数をテストする

Last updated at Posted at 2018-01-30

非同期関数をTestRunnerで実行したところ常にPassしてしまってとまどったのでその結果をサンプルとして残しておきます。

Test_AsyncBehavior.cs
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Threading;
using System.Threading.Tasks;
using System.Collections;
public class Test_AsyncBehavior : MonoBehaviour
{
    ///非同期関数を使うユースケース
    void Start()
    {
        Task.Run(Function);
        var a = 10;
        Debug.Log(a);
        var result = Task.Run<int>(() => { return CalcFunction(a); }).Result;
        Debug.Log(result);
    }

    //Asyncに文字出力をする関数
    private async Task Function()
    {
        Debug.Log("begin function()");
        for (var i = 0; i < 5; ++i)
        {
            await Task.Delay(1000);
            Debug.Log(i);
        }
        //親がWaitしない場合にはこれ以前にTestが終了するためPassする
        //Assert.IsFalse(true);
        Assert.IsTrue(true);
        //親がWaitしない場合にはここまで到達しない。
        Debug.Log("end function()");
    }

    //Asyncに渡された数の2乗を結果として返す関数
    private async Task<int> CalcFunction(int n)
    {
        await Task.Delay(3000);
        //これは失敗する
        //Assert.IsTrue(false);
        return n * n;
    }

    /// 非同期関数のテスト
    [Test]
    public void Test_Asyncs()
    {
        //当然成功
        Assert.AreEqual(10, 10);
        //当然失敗
        //Assert.AreEqual(10, 20);
        //中にAssertを持つ関数を呼び出す
        var task = Task.Run(Function);
        Debug.Log("runs async function.");
        //非同期関数を呼び出して待つ
        var result = Task.Run<int>(() => { return CalcFunction(4); }).Result;
        Debug.Log("runs async calculation 4x4.");
        //成功
        Assert.AreEqual(16, result);
        Debug.Log("pass result of calculation.");
        //失敗する
        //Assert.AreEqual(25, result);
        //これをしないとFunctionの実行完了をまたずにTestを通過する
        task.Wait();
    }
}

問題となったのは

        var task = Task.Run(Function);
        ...
        task.Wait();

の部分で、Waitしてあげないと先にTestが終了してPassしてしまうよ、という至極当然なつまづきでした。このへん怪しいので次はPlaymodeのテストを書いてみたいです。

参考

Unity Document TestRunner

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2