The First Mock

When a type is mocked, all instances of the type will have the ability to intercept its methods. This ability can be used when you want to test that a certain method was called but you do not actually want to run the code in that method. 

To do that you have to:

  1 Mock the class.
  2 Intercept the method (this phase is called Expectations, as you tell Typemock Isolator what calls you expect).
  3 Verify that all expected methods were called (this acts the same as regular mock objects).
Example - Simple Mocking

In this example, an Authentication class internally calls a Logger. You want to mock the Logger (i.e., intercept the calls and not run the original code) and verify that it was called the correct amount of times.

Here is the Authentication code:

Hide C# Code
Hide Visual Basic Code
// C#
public bool IsAuthenticated(string name,string password)
{
      Logger.Log(Logger.NORMAL,"Entering Authentication");
      try 
      {
            // do something
            int Results = DoSelect(statement);
            bool isOk = Results==1;
            if (isOk) 
            {
                  Logger.Log(Logger.NORMAL,"User Authenticated "+name);
            } 
            else 
            {
                  Logger.Log(Logger.SECURITY,"User login failed "+name);
            }
            return isOk;
      } 
      catch (Exception ex) 
      {
            Logger.Log(Logger.FAILED,"Login system failure",ex);
            // handle exception
      }
}

' Visual Basic
Public Function IsAuthenticated(name As String,password As String) As Boolean
      Logger.Log(Logger.NORMAL,"Entering Authentication")
      Try 
            ' do something
            Dim Results As Integer = DoSelect(statement)
            Dim isOk As Boolean = Results = 1
            If isOk Then
                  Logger.Log(Logger.NORMAL,"User Authenticated "+name)
            Else 
                  Logger.Log(Logger.SECURITY,"User login failed "+name)
            End If
            IsAuthenticated = isOk
      Catch ex As Exception
            Logger.Log(Logger.FAILED,"Login system failure",ex);
            ' handle exception
      End Try
End Function

And here is the test:

// C#
[Test] public void Authenticated ()
{
      Authentication authenticator = new Authentication();
      // Initialize Type Mocks (This can be done in the [Setup])
      MockManager.Init ();
      // the Logger class is now being mocked
    1 Mock logMock = MockManager.Mock(typeof(Logger)); 
      // set up our expectations for 2 Log calls in IsAuthenticated
      // 1) "Entering Authentication" Log at first line
      // 2) "User login failed user" Log
    2 logMock.ExpectCall("Log");
      logMock.ExpectCall("Log");
     
      // authentication should fail
      Assert.IsFalse(authenticator.IsAuthenticated("user","password"));        
      // Verify that all calls were made (This can be done in the [Teardown])
    3 MockManager.Verify();
}

' Visual Basic
<Test()> Public Sub Authenticated ()
      Dim authenticator As Authentication = new Authentication
      ' Initialize Type Mocks (This can be done in the <Setup>)
      MockManager.Init()
      ' the Logger class is now being mocked
    1 Dim logMock As Mock = MockManager.Mock(GetType(Logger)) 
      ' set up our expectations for 2 Log calls in IsAuthenticated
      ' 1) "Entering Authentication" Log at first line
      ' 2) "User login failed user" Log
    2 logMock.ExpectCall("Log")
      logMock.ExpectCall("Log")
     
      ' authentication should fail                  
      Assert.IsFalse(authenticator.IsAuthenticated("user","password"))        
      ' Verify that all calls were made (This can be done in the <Teardown>)
    3 MockManager.Verify()
End Sub

This is what we did:

  1 Set up mocking of the Logger; the next new Logger instance will be mocked and all static calls will be intercepted.
In this case, the logger's static method IsAuthenticated is called.
  2 Expected IsAuthenticated to write the correct logs to the Logger. Two calls are expected.
  3 Verified that all expected methods where called (this acts the same as regular mock objects).


To run the example, you can type in the following: tmockRunner nunit-console.exe test.dll.

To set the expectation for more than one call, use the timesToRun parameter, so that the code in 2 above is equivalent to logMock.ExpectCall("Log",2).

To set expectations of overloaded methods, use Conditional Expectations.


Copyright © Typemock Ltd. 2004-2010. All Rights Reserved.