【发布时间】: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