Created
May 16, 2025 14:22
-
-
Save AArnott/bdf9402f41f436322d0fb38228fbfd17 to your computer and use it in GitHub Desktop.
Fail tests instead of crashing the test host in .NET test processes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Diagnostics; | |
using System.Runtime.CompilerServices; | |
internal static class AvoidCrashingOnDebugAsserts | |
{ | |
[ModuleInitializer] | |
internal static void Initializer() | |
{ | |
if (Trace.Listeners.OfType<DefaultTraceListener>().FirstOrDefault() is { AssertUiEnabled: true } defaultListener) | |
{ | |
// Avoid crashing the test process. | |
defaultListener.AssertUiEnabled = false; | |
} | |
// But _do_ throw an exception so the scenario fails. | |
Trace.Listeners.Add(new ThrowListener()); | |
} | |
private class ThrowListener : TraceListener | |
{ | |
public override void Fail(string? message) | |
{ | |
throw new Exception($"Test failed: {message}"); | |
} | |
public override void Fail(string? message, string? detailMessage) | |
{ | |
throw new Exception($"Test failed: {message}. {detailMessage}"); | |
} | |
public override void Write(string? message) | |
{ | |
} | |
public override void WriteLine(string? message) | |
{ | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment