Skip to content

Instantly share code, notes, and snippets.

@AArnott
Created May 16, 2025 14:22
Show Gist options
  • Save AArnott/bdf9402f41f436322d0fb38228fbfd17 to your computer and use it in GitHub Desktop.
Save AArnott/bdf9402f41f436322d0fb38228fbfd17 to your computer and use it in GitHub Desktop.
Fail tests instead of crashing the test host in .NET test processes
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