はなちるのマイノート

Unityをメインとした技術ブログ。自分らしくまったりやっていきたいと思いますー!

【Unity】Unity Test Frameworkでログ出力のテストをする方法(特にDebug.LogError, Debug.LogException)

はじめに

今回はログ出力のテスト方法について紹介をしようと思います。

ログ出力をしている例

概要

Unity Test FrameworkではDebug.LogErrorDebug.LogExceptionが実行されるとテストが失敗になる仕様にデフォルトでなっています。

一応それをやめるフラグであるLogAssert.ignoreFailingMessagesなるものがあります。

public static bool ignoreFailingMessages ;

Set this property to true to prevent unexpected error log messages from triggering an assertion. This property is set to false by default.

TestTools.LogAssert-ignoreFailingMessages - Unity スクリプトリファレンス

ただしパッと調べた感じ2019.2あたり?(要調査)から廃止されてしまったみたいです。

ではどうやってDebug.LogErrorDebug.LogExceptionをテストすればよいのかというと、LogAssert.ExpectLogAssert.NoUnexpectedReceivedを利用することで実現できます。

Expect a log message of a specfic type. If an error, assertion or exception log is expected, the test will not fail. The test will fail if a log message is expected but does not appear.

// DeepL翻訳
指定した型のログメッセージを期待する。エラーログ、アサーションログ、例外ログが期待される場合は、 テストは失敗しません。ログメッセージが期待されているにもかかわらず表示されない場合は、 テストは失敗します。

TestTools.LogAssert-Expect - Unity スクリプトリファレンス

Triggers an assert if any logs have been received that were not expected. Returns without asserting if all logs received so far have been registered as expected.

// DeepL翻訳
予想外のログを受け取った場合にアサートする。これまでに受け取ったログがすべて期待通りに登録されていた場合は、 アサートせずに返します。

TestTools.LogAssert-NoUnexpectedReceived - Unity スクリプトリファレンス

実際にテストした例を見ながら使い方を見ていきます。

テスト方法

[Test]
public void SimplePasses()
{
    // 例外ログが出力されているか調べる
    LogAssert.Expect(LogType.Exception, "Exception: Exception of type 'System.Exception' was thrown.");
        
    Debug.LogException(new Exception());
        
    // LogAssert.Exceptしていないログが出力されていたらFaildにする
    LogAssert.NoUnexpectedReceived();
}
実行した様子
public static void Expect(LogType type, string message)
public static void NoUnexpectedReceived()

messageにはコンソールに出力されるログメッセージを記載します。

LogTypeについては以下の通り。

public enum LogType
{
    /// <summary>
    ///   <para>LogType used for Errors.</para>
    /// </summary>
    Error,
    /// <summary>
    ///   <para>LogType used for Asserts. (These could also indicate an error inside Unity itself.)</para>
    /// </summary>
    Assert,
    /// <summary>
    ///   <para>LogType used for Warnings.</para>
    /// </summary>
    Warning,
    /// <summary>
    ///   <para>LogType used for regular log messages.</para>
    /// </summary>
    Log,
    /// <summary>
    ///   <para>LogType used for Exceptions.</para>
    /// </summary>
    Exception,
}