Throwing special type of exception to terminate unit test

Posted by trendl on Stack Overflow See other posts from Stack Overflow or by trendl
Published on 2010-05-21T16:24:53Z Indexed on 2010/05/21 16:30 UTC
Read the original article Hit count: 147

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.

© Stack Overflow or respective owner

Related posts about unit-testing

Related posts about best-practices