Hello @aik,
Thank you for taking time to post your question on Microsoft Q&A forum.
You can get exceptions from test in [TestCleanup], but for [TestInitialize] and some other attributes, this doesn’t work.
I would like to share a ticket with you => UnhandledExceptionEventHandler in MSTest doesn’t show the exception.
Extract some parts of the dialogues here:
MSTest framework, as most test framework, is catching "all" exceptions that occurs (on the same thread) during "test method" execution and consider test as failed. Because all the exceptions are caught, it’s expected that the
AppDomain.UnhandledException
doesn’t trigger as there is no uncaught exception. If the exception happens on a different thread then theUnhandledException
will be triggered.
If the
[TestMethod]
fails you can check in[TestCleanup]
and log it (and take a screenshot of the page, which is usually very helpful). However, if it fails in[TestInitialize]
or[TestCleanup]
you cannot check it and are forced to wrap the whole method in atry-catch
to make sure everything went OK or take a screenshot otherwise.
I think you have some misconceptions about the unhanded handlers work. As we are directly catching the exception it would never bubble up in this path and this is the correct behavior.
Would it be feasible for MSTest to provide an UnhandledException event handler at the TestClass level?
Technically we could provide some handler (cannot be
Unhandled
because the exceptions are handled) but what would you do? What I mean is that eventing system is a trigger not awaited so by the time you act on it, it’s possible we have disposed the class, or run some other method that would change the state.
Now if you would like to easily inject some
TestCleanup
method behavior in all classes, this is something that would be different, would be part of the workflow (and awaited) giving you a change to act. And given some discussions we had would be indeed something valuable. Note that for the time being, if all your tests inherit from a base class with suchTestCleanup
method, it would be called always and would help you have this feature already.
Sincerely,
Tianyu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.