如何在MSTest中处理currentDomain.UnhandledException

Tom*_*bes 8 c# multithreading unit-testing mstest unhandled-exception

我尝试基于回答实现解决方案如何处理单元测试时在其他线程中引发的异常?,但我仍然不明白在处理程序中要做什么.我们假设我有一个测试:

[TestMethod]
void Test()
{
    new Thread(() => { throw new Exception(); }).Start();
}
Run Code Online (Sandbox Code Playgroud)

我有和所有测试的全局初始化:

[AssemblyInitialize]
public static void AssemblyInitialize(TestContext context)
{
    AppDomain currentDomain = AppDomain.CurrentDomain;
    currentDomain.UnhandledException += currentDomain_UnhandledException;       
}

static void currentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    Exception ex = e.ExceptionObject as Exception;
    if (ex != null)
        Trace.WriteLine(ex);

        Assert.Fail("Unhandled Exception in thread.");
}
Run Code Online (Sandbox Code Playgroud)

问题是Assert.Fail实际上抛出异常,它再次被currentDomain_UnhandledException捕获并导致MSTest崩溃(stackoverflow?).我不想捕获Assert.Fail,但我想让测试失败.怎么解决?

我知道我可以捕获异常并在测试的主线程上调用它,但我需要全局解决方案进行数千次测试.我不想让每一个测试都复杂化.

hth*_*tho 0

这是我解决问题的方法:

        private List<(object sender, UnhandledExceptionEventArgs e)> _UnhandledExceptions;
        [TestInitialize()]
        public void Initialize()
        {
            _UnhandledExceptions = new List<(object sender, UnhandledExceptionEventArgs e)>();
            AppDomain.CurrentDomain.UnhandledException += (sender, e) => {
                _UnhandledExceptions.Add((sender, e));
            };
        }
        [TestCleanup()]
        public void Cleanup()
        {
            if (_UnhandledExceptions.Count != 0) Assert.Fail($"There were {_UnhandledExceptions.Count} unhandled Exceptions! <{string.Join(">," + Environment.NewLine + "<", _UnhandledExceptions.ToArray().Select(ev => ev.e.ExceptionObject))}>.");
        }
Run Code Online (Sandbox Code Playgroud)

我选择了Assert.fail因为Assert.AreEqual(0它分散了对实际问题的注意力。(太糟糕了,没有CollectionAssert.IsEmpty()方法可以在错误时实际打印集合。