单元测试时如何处理其他线程中引发的异常? [英] How to handle exceptions raised in other threads when unit testing?
问题描述
使用Visual Studio Team测试时测试中未处理的异常被捕获并在结果中报告。所以我很惊讶看到测试托管过程(VSTestHost.exe)崩溃,并显示系统崩溃对话框。
When testing with Visual Studio Team Test unhandled exceptions in tests are caught and reported in the results. So I was kind of surprised to see the test hosting process (VSTestHost.exe) crash and showing the system crash dialog.
进一步调查,这个崩溃是一个未处理的异常在另一个线程(更直接,它是一个异步套接字回调)。事实上这样的东西崩溃了托管过程:
Upon further investigation this crash was an unhandled exception raised in another thread (more directly, it was an async socket callback). And indeed something like this crashes the hosting process:
[TestMethod]
void Test()
{
new Thread(() => { throw new Exception(); }).Start();
}
任何建议我应该做什么?
Any advices what I should do there?
- 如果我只是用它,说任何代码分发/签入应该至少测试一次,所以这样的事情很可能会被捕获?
- 我应该尝试安装全局异常处理程序,并检查其在每种拆卸方法中的状态吗?
- 或者可能已经存在帮助这个的东西?
推荐答案
您可以使用全局异常处理程序捕获AppDomain中所有未捕获的异常:
You can use a Global Exception handler to catch all of the uncaught exception in the AppDomain:
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new EventHandler(UnhandledExceptionHandler);
我认为它也适用于从其他线程抛出的异常
I think it would work for exceptions thrown from other threads as well
这篇关于单元测试时如何处理其他线程中引发的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!