如何在MSTest中处理currentDomain.UnhandledException

14

我尝试根据答案 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实际上会抛出异常,而当前域的UnhandledException又会再次捕获它,这会导致MSTest崩溃(堆栈溢出?)。我不想捕获Assert.Fail,但我想让测试失败。如何解决?

我知道我可以捕获异常并在测试的主线程上调用它,但我需要一个全局解决方案来处理成千上万个测试。我不想让每个单独的测试变得更加复杂。


你可以简单地检查异常对象是否为Assert.Fail异常,而不是再执行另一个Assert.Fail吗? - John Koerner
1个回答

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

我选择使用Assert.fail而不是Assert.AreEqual(0),因为后者会分散注意力,无法解决实际问题。(很遗憾没有CollectionAssert.IsEmpty()方法,可以在出错时打印集合。)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接