如何在 MSTest 中处理 currentDomain.UnhandledException [英] How to handle currentDomain.UnhandledException in MSTest

查看:59
本文介绍了如何在 MSTest 中处理 currentDomain.UnhandledException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried to implement solution based on answer How to handle exceptions raised in other threads when unit testing?, but I still don't understand what to do in the handler. Let's suppose I have a test:

[TestMethod]
void Test()
{
    new Thread(() => { throw new Exception(); }).Start();
}

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

I have and global initialization of all tests:

[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.");
}

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

The problem is that Assert.Fail actually throws exception which is again caught by the currentDomain_UnhandledException and it causes MSTest to crash (stackoverflow?). I don't want to catch Assert.Fail, but I want to make the test failed. How to resolve it?

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

I know I could catch the exception and invoke it on test's main thread, but I need global solution for thousand tests. I don't want not to complicate every single test.

推荐答案

这是我解决问题的方法:

Here is my approach to the problem:

        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))}>.");
        }

我选择 Assert.fail 而不是 Assert.AreEqual(0,因为它分散了实际问题的注意力.(可惜没有 CollectionAssert.IsEmpty() 方法,它实际上在出错时打印集合.

I choose Assert.fail over Assert.AreEqual(0 because it distracts from the actual problem. (Too bad there is no CollectionAssert.IsEmpty() method, that actually prints the collection on error.

这篇关于如何在 MSTest 中处理 currentDomain.UnhandledException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆