0

I had a unit test (MSTest) that threw an exception and triggered the AppDomain.CurrentDomain.UnhandledException event.

This worked in .Net Framework 4.8 (the method DoSmthwas called):

AppDomain.CurrentDomain.UnhandledException += (_, args) => DoSmth();

var thread = new Thread(() => throw new DataException("This is just a system test")); // necessary. Otherwise, the unit test framework will see the exception and the test fails.
thread.Start();
thread.Join();

But it does not work in .Net5 or 6.

The whole test execution crashes with:

The active test run was aborted. Reason: Test host process crashed : Unhandled exception. System.Data.DataException: This is just a system test

Does someone know how to fix it for .Net5/6?

hardfork
  • 2,470
  • 1
  • 23
  • 43
  • 1
    `UnhandledException` doesn't actually handle the exception, so the process crashes in any case. It's just that apparently, in earlier versions, this still allowed the test to execute, while the new versions have special behavior for a host process crash. I'd say that there's not really any way around this other than either making sure the exception does not go completely unhandled (which is a good idea anyway); conceivably you could also try to make sure the test runs in its own child process and do IPC, but this is *far* more complicated and essentially has you writing your own test harness. – Jeroen Mostert May 16 '22 at 08:58
  • Legacy versions of mstest [ignored unhandled exceptions](https://stackoverflow.com/questions/21903711/why-an-unhandled-exception-on-a-unittest-does-not-make-it-fail-using-mstest) in any thread that was not started by the test runner. Not exactly a desirable feature btw. The legacy framework allowed for this with the `legacyUnhandledExceptionPolicy` config parameter, or custom CLR host, resurrecting .NET 1.x behavior. That's all done away with in .NETCore, inevitably you'll always terminate the test runner. No possible workaround, beyond "don't do it". – Hans Passant May 16 '22 at 11:52

0 Answers0