我尝试根据答案 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