How to handle currentDomain.UnhandledException in MSTest

瘦欲@ 提交于 2019-12-23 07:46:17

问题


I tried to implement solution based on answer How to handle exceptions raised in other threads when unit testing?, but I still don't understand what to do in the handler. Let's suppose I have a test:

[TestMethod]
void Test()
{
    new Thread(() => { throw new Exception(); }).Start();
}

I have and global initialization of all tests:

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

The problem is that Assert.Fail actually throws exception which is again caught by the currentDomain_UnhandledException and it causes MSTest to crash (stackoverflow?). I don't want to catch Assert.Fail, but I want to make the test failed. How to resolve it?

I know I could catch the exception and invoke it on test's main thread, but I need global solution for thousand tests. I don't want not to complicate every single test.

来源:https://stackoverflow.com/questions/38309657/how-to-handle-currentdomain-unhandledexception-in-mstest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!