Throwing special type of exception to terminate unit test
- by trendl
Assume I want to write a unit test to test a particular piece of functionality that is implemented within a method. If I wanted to execute the method completely, I would have to do some extra set up work (mock objects expectations etc.). Instead of doing that I use the following approach:
- I set up the expectations I'm interested in verifying and then make the tested method throw a special type of exception (e.g. TerminateTestException).
- Further down in the unit test I catch the exception and verify the mock object expectations.
It works fine but I'm not sure it is good practice. I do not do this regularly, only in cases where it saves me time and effort. One thing that comes to mind as an argument against using this is that throwing exceptions takes long time so the tests execute slower than if I used a different approach.