问题
I have a base class that has a TestInitialize and a TestCleanup in it. I then have other test classes which inherit from this class. The TestCleanup is supposed to perform certain actions when a test from the derived class fails.
The TestCleanup gets executed when the test fails in the actual test. However, when the test fails in the TestInitialize, the TestCleanup doesn't even get executed. Why does this happen and is there a way to get the TestCleanup to get called anyway?
I don't think that the fact that the TestInitialize and TestCleanup are in a base class is at all causing this issue, I just wanted to give more information just in case it was.
回答1:
This is a known issue. It looks like it has been reported to Microsoft connect.
http://connect.microsoft.com/VisualStudio/feedback/details/694337/testcleanup-method-does-not-run-when-it-should
回答2:
In my Opinion you shouldn't write code in the TestInitialize that can fail.
If you think what you are doing is correct, and you just want to catch it if it fails, why not wrapping the TestInitialize with a try-catch and call your code or TestCleanup on exception?
回答3:
We have a try catch in our TestInitialize. Its for coded UI tests and if you dont kill the application/browser you will have multiple windows open next time you connect to the testenvironment (if you are deploying and testing on one of those).
There are alot of things that can go wrong in the testinitialize when talking about CodedUI so use a TryCatch, and call the TestCleanup manually in the Catch. More correct is that in the Catch we kill the application/browser in the same way that the TestCleanup would do. We dont call the cleanup function. But if you can, then do so.
来源:https://stackoverflow.com/questions/17788466/when-mstest-fails-in-testinitialize-why-doesnt-testcleanup-get-executed