Stop Debug Messages from Disrupting Unit Tests

When writing code, I frequently add Debug checks to alert me that an incorrect assumption has been made. During development (debug build code), I want to know I haven’t handled a case. During production (release build code), I don’t want to interrupt the user experience. This means that for an unhandled case, the method should be written to provide safe values in all cases if that is the desired result.

In the example below, value is initialized to a safe value before the case statement. If format is an unhandled value, we will display a debug popup in debug builds. Here is an example:

switch (format)
{
    case x:
        value = 0;
        break;
    case y:
        value = 1;
        break;
    default:
        // Unhandled format value.
        Debug.Fail($"Unhandled format value: {format}");
        break;
}

This works well except for when I want to run automated Unit Tests. In that case, I don’t want a popup to display and wait for user input that will never come. To disable the popups, you can remove all the Trace listeners so the Debug.Fail() message is never caught. I this case, I am disabling the popup logic once in the Unit Test assembly initialization method.

[AssemblyInitialize()]
public static void AssemblyInit(TestContext context)
{
    // Disable any Debug/Trace messages like Debug.Fail() method.
    Trace.Listeners.Clear();
}

There are those who might consider this approach too heavy-handed and will retrieve the list of listeners and modify the AssertUiEnabled flag to false. I tried this but I never got it working since the default listener already had that setting.