c# - 如何在 MSTest 中处理 currentDomain.UnhandledException

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

我试图根据答案实现解决方案 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?)。我不想 catch Assert.Fail,但我想让测试失败。如何解决?

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

最佳答案

这是我解决问题的方法:

        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.failAssert.AreEqual(0因为它分散了对实际问题的注意力。 (太糟糕了,没有 CollectionAssert.IsEmpty() 方法,它实际上在错误时打印集合。

关于c# - 如何在 MSTest 中处理 currentDomain.UnhandledException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38309657/

相关文章:

c# - 获取点和原点之间的角度

unit-testing - MSTest Environment.CurrentDirectory 不正确 VS 2012

c# - 为什么完全由CPU约束的进程与超线程一起工作会更好?

python - Python 中的单元测试问题 "Imperative shell, functional core"

unit-testing - assert_called_once() 或 assert_called_xyz().... 等效?

c# - 提取版本号

c# - 从 datagridview 更新 SQL Server 数据库

C#.Net : Why is my Process. Start() 挂起?

c# - 开始调用错误

java - 在 J2EE 中的上下文监听器中运行线程是否相关?