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.
EDIT:
Just to clarify, I'm not modifying the SUT code. What I do I provide a mock object or override the SUT class so that the SUT quits execution after the part I'm interested in is executed.
private class TestCalculationService : CalculationService
{
public bool ValidateForSyncCalled;
protected override void ValidateForSyncCall()
{
ValidateForSyncCalled = true;
throw new ExceptionToTerminateTest();
}
}
[TestMethod]
public void CalculationService_Calculate_Sync_Calls_ValidateForSyncCall()
{
InitializeMocks();
TestCalculationService calculationService = new TestCalculationService();
calculationService.MessageInstanceFactory = _mockMessageInstanceFactory;
try
{
calculationService.Calculate( null);
Assert.Fail("Exception should have been thrown");
}
catch (ExceptionToTerminateTest)
{
//ok
}
Assert.IsTrue(calculationService.ValidateForSyncCalled );
}