【问题标题】:How to handle currentDomain.UnhandledException in MSTest如何在 MSTest 中处理 currentDomain.UnhandledException
【发布时间】:2016-11-13 13:27:39
【问题描述】:

我尝试根据答案How to handle exceptions raised in other threads when unit testing? 实施解决方案,但我仍然不明白在处理程序中要做什么。假设我有一个测试:

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

我已经对所有测试进行了全局初始化:

[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,但我想让测试失败。如何解决?

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

【问题讨论】:

  • 您能否简单地检查异常对象以查看它是否是Assert.Fail 异常而不执行另一个Assert.Fail

标签: c# multithreading unit-testing mstest unhandled-exception


【解决方案1】:

这是我解决问题的方法:

        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() 方法,它实际上会在错误时打印集合。

【讨论】:

    猜你喜欢
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多