I'm looking for a way to catch exceptions globally in my NUnit project class library. So if one of my unit tests throws an exception, I can catch it in one spot. I don't want to surround each of my tests with a try/catch block. The reason I'm doing this is to print a nice error message with an explanation of the stack trace. In ASP.NET they have a method called Application_Error in Global.asax that does this sort of thing.
The extension object passed to Install must implement the EventListener interface:
Here is how it works:
The method Try accepts the code as a parameter and executes it in the try block. So, in the catch block you can apply any necessary formatting.
The method TestO1 is just a usual unit test without any tricks.
The TestO2 has the assertion wrapped with the method Try:
Try( () => any line of code here );
It will be the same try/catch, but now I don’t need to write a lot of ugly code.