.Net 5 Test Host Crashes when Exception is thrown in a thread

Viewed 384

This is the error I get:

========== Starting test run ==========
NUnit Adapter 4.2.0.0: Test execution started
Running selected tests in C:\Users\itaib\source\repos\TestHostCrashTest\TestHostCrashTest\bin\Debug\net5.0\TestHostCrashTest.dll
   NUnit3TestExecutor discovered 1 of 1 NUnit test cases using Current Discovery mode, Non-Explicit run
The active test run was aborted. Reason: Test host process crashed : Unhandled exception. System.Exception: some value
   at TestHostCrashTest.CrashTest.<>c.<CrashTestHost>b__0_0() in C:\Users\itaib\source\repos\TestHostCrashTest\TestHostCrashTest\CrashTest.cs:line 14
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

========== Test run aborted: 0 Tests (0 Passed, 0 Failed, 0 Skipped) run in < 1 ms ==========

when I run this test:

using NUnit.Framework;
using System.Threading;

namespace TestHostCrashTest
{
    public class CrashTest
    {
        [Test]
        public void CrashTestHost()
        {
            var t = new Thread(() =>
                throw new Exception("some value")
            );

            t.IsBackground = true;
            t.Start();
            t.Join();
        }
    }
}

It works well on .net framework 4.6.1 but crashes .net 5.0.

I tried registering AppDomain.CurrentDomain.UnhandledException with nothing in it but it didn't work. Unfortunately handling the exception gracefully isn't an option at this point.

Any workarounds?

BTW this is the .csproj file:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <!--<TargetFramework>net461</TargetFramework>-->
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
    <PackageReference Include="NUnit" Version="3.13.2" />
    <PackageReference Include="NUnit3TestAdapter" Version="4.2.0" />
  </ItemGroup>
</Project>
1 Answers

When you configure your test host, you need to be sure that you are starting your TestHost with app Middleware, because otherwise exceptions are not handled and they will be thrown in tests.

Related