GameDriver provides a means of catching Unity's logged messages, which can be particularly useful for test cases in which exceptions and other relevant log events are regular occurrences. By using an event included in the GameDriver API, an exception can be caught and reacted to as a part of the test.


Catching Logged Messages


To react to a log message thrown by Unity as a part of your tests you must first register a method or callback to the "UnityLoggedMessage" event that is provided by the GameDriver API.


api.UnityLoggedMessage += (s, e) =>
{
    File.WriteAllLines(@"c:\TestLogs\TestOutput.txt", new string[] { $"Type: 
    {e.type.ToString()}\r\nCondition: {e.condition}\r\nStackTrace: {e.stackTrace}" });
};

In the above example, we are registering a callback that will write the details of the message to an output file. The parameter 'e' in this case represents a "UnityLogEventEventArgs", a type of event that acts as a container for useful information regarding the caught log information, such as the log message type (error, exception, warning, etc.), condition (such as the type of exception), and associated stack trace.


You could even build your test conditions around potentially thrown exceptions.

bool caughtException = false;

api.UnityLoggedMessage += (s, e) =>
{
    if (e.type == LogType.Exception && e.condition == "NullReferenceException: Object reference not set to an instance of an object")
    {
        TestContext.Progress.WriteLine(e.stackTrace);
        caughtException = true;
    }
}

Assert.IsFalse(caughtException);

The above test would only pass if a "NullReferenceException" was not thrown. This can be adapted to encompass any array of exceptions or log messages relevant to your test cases. 


Note: If you would like to output to the console from within a callback, be sure to use TestContext.Progress.WriteLine instead of the more commonly used Console.WriteLine, as shown above.