Throwing Exceptions with Natural Mocks™
When you want to test how your class behaves when an exception is
thrown, you can mock an exception when a mocked method is called. In
the following example, an exception is thrown when the mocked
statement is called.
Example - Throwing Exceptions
Let's assume you want to test how IsAuthenticated, from the First Mock topic example, behaves when the Log method throws an exception. Here is how you do it by changing our code at position 2 .
// C#
[Test] public void Authenticated ()
{
Authentication authenticator = new Authentication();
// set up our expectations for 2 Log calls in IsAuthenticated
1 using (RecordExpectations recorder = RecorderManager.StartRecording())
{
// CAUTION: ALL calls here are mocked!!!
2 Logger.Log(Logger.NORMAL,"Entering Authentication")
recorder.Throw(new Exception());
// Here is another way to mock throwing exceptions
recorder.ExpectAndThrow(Logger.Log(Logger.NORMAL,"Entering Authentication"),new Exception());
}
authenticator.IsAuthenticated("user","password");
}
' Visual Basic
<Test()>
Public Sub Authenticated ()
Dim authenticator
As Authentication =
new Authentication
' For .NET 2.0 (.NET 1.1 Syntax)
' set up our expectations for 2 Log calls in IsAuthenticated
1 Using recorder
As New RecordExpectations
' CAUTION: ALL calls here are mocked!!!
2 Logger.Log(Logger.NORMAL,"Entering Authentication")
recorder.
Throw (
New Exception);
' Here is another way to mock throwing exceptions
recorder.
ExpectAndThrow (
Logger.Log(Logger.NORMAL,"Entering Authentication"),
New Exception)
End Using
' Thats it folks
authenticator.IsAuthenticated("user","password")
End Sub
In this example, Logger.Log will always throw an exception when called.
Copyright © Typemock Ltd. 2004-2010. All Rights Reserved.