简体   繁体   中英

MsTest TestCleanup method not called when an unhandled exception is thrown

I have a test which uses an external assembly to access UI features in the application we're testing. This assembly throws an exception of its own custom type if the UI is not in the appropriate state.

I've set up a TestCleanup method that kills the application's process (while a TestInitialize starts it) so that after a test run has been completed, the UI is restarted with a clean state.

This work well under regular conditions, however, whenever an exception from the referenced assembly is thrown, it never gets to the cleanup method and jumps straight ahead to the next test. This doesn't happen with exceptions thrown from the test itself, like AssertFailedException. I even tried throwing a basic Exception from the test, and it got to the cleanup method.

不幸的是,这与 C# 在构造函数中处理异常的方式不同:发生这种情况时,将调用终结器。

But you can directly call CleanUp method from the catch block

        [TestCleanup]
        public void Clenup()
        {
               ..............
        }


        [TestMethod]
        public void Test1()
        {
            try
            {...................}
            catch (Exception e)
            {
                 Cleanup();
                 throw new Exception();
            }
         }

That was fixed in MsTest v2.

https://github.com/Microsoft/testfx/issues/250

Extract from the above link:

This was a conscious compat break to give unit test writers a choice to cleanup partially initialized methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM