I am looking for a way to modify catch block depending on if it’s executed during the unit test run or not. The purpose is basically to detect/setup mock expectations which are swallowed because catch doesn’t rethrow.
I am using MSTest.
One obvious thing is using preprocessor but I don’t think it works. Especially if to use DEBUG define. There should be an easy way to detect that, shouldn’t it? I must have been looking for something wrong because I couldn’t find much info on that.
try {...}
catch(Exception)
{
Log(...);
#if DEBUG
throw;
#endif
}
ANSWER: extract the body of the try into another method and test that instead. Provided by Jon and Ritch. See discussion under Jon’s answer. Though thanks everyone for the contribution.
How can you test the exception handling if you want to change the exception handling? Testing the altered behaviour doesn’t test what would happen if you didn’t alter the behaviour.
Hopefully your mocks have other ways of allowing you to validate expectations at the end of the test, so you can avoid the exception being ignored that way – and you should be testing that your Log and Fix really does happen when you want it to. (Testing logging is tedious and rarely worth it, but presumably Fix does something important.) You should also be testing that the exception isn’t rethrown, if that’s part of the design.
(As a side matter, catching
ArgumentExceptionis usually a bad sign to start with. But maybe in this case it’s due to a poorly-designed library you have to use.)EDIT: Just as a thought, if you’re going to be able to test Log and Fix, that means you have to be able to check whether or not they were invoked. In cases where you don’t expect an exception to be thrown, you should be able to verify that they weren’t called. If they were, you’ve effectively proved that an exception was thrown.