Unity Log Message/Exception Handling with GameDriver

Learn how to catch logged messages from Unity into your GameDriver test

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 were not thrown. This can be adapted to encompass an array of exceptions or log messages relevant to your test cases.

In the example below, e.type will allow you to filter based on the message type such as Log, Warning, Debug, or Error. To filter for a specific message type, check the type and only add to a final message, such as:

api.UnityLoggedMessage += (s, e) =>
{
if(e.type == LogType.Warning)
{
Console.WriteLine($"Type: {e.type.ToString()}\r\nCondition: {e.condition}\r\nStackTrace: {e.stackTrace}");
}
};

Update the GDIOAgent config to enable additional Unity log levels to be published to the API. Simply add the following line to the Assets\GDIO\Resources\config\gdio.unity_agent.config.txt file:

<config><unitymessagefilter include="0,1,4" /></config>

Log levels are as follows:

0 = Error

1 = Assert

2 = Warning

3= Log

4 = Exception

Note: If you want to output to the console from within a callback, use TestContext.Progress.WriteLine instead of the more commonly used Console.WriteLineas shown above.