Throwing Exceptions

When you want to test how your class behaves when an exception is thrown, you can mock an exception when the mocked method is called. In the following example, the Always expectations is used to mock all calls to the method.

Example - Throwing Exceptions

Let's assume we 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 you code at position 2 and using AlwaysThrow.

Hide C# Code
Hide Visual Basic Code
// C#
[Test] public void Authenticated ()
{
      Authentication authenticator = new Authentication();
      MockManager.Init ();
      // the Logger class is now being mocked
    1 Mock logMock = MockManager.Mock(typeof(Logger)); 
      // set up our expectations 
    2 logMock.AlwaysThrow("Log", new Exception());
     
      authenticator.IsAuthenticated("user","password");        
}

' Visual Basic
<Test()> Public Sub Authenticated ()
      Dim authenticator As Authentication = new Authentication
      MockManager.Init()
      ' the Logger class is now being mocked
    1 Dim logMock As Mock = MockManager.Mock(GetType(Logger)) 
      ' set up our expectations 
    2 logMock.AlwaysThrow("Log", New Exception)
     
      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.