Sample 2: Testing Interaction between Two Classes

This sample shows a test of the interaction between two classes:

SomeClass, which has a shared sub called MyMethod.

UserOfSomeClass, which has a sub called DoSomething.

This test checks that every exception thrown from SomeClass is shown to the user using MessageBox.

APIs Used

API

Description

Isolate.WhenCalled(..).WillThrow (C#) TheseCalls.WillThrow (VB)

The method inside the Isolate.WhenCalled() will throw a specified exception when the method is called.

Isolate.WhenCalled(..).WillReturn (C#) TheseCalls.WillBeIgnored (VB)

The method inside the Isolate.WhenCalled() will be ignored and return a fake value.

Isolate.Verify.WasCalledWithExactArguments (C# and VB)

Verify that the method inside the Isolate.WhenCalled() was called during the test with the exact arguments.

Scenario

1. Set a behavior: when MyMethod() is called, throw a specified exception.

2. Define that all calls to MessageBox.Show() are ignored and return a fake value.

3. Create a new instance of UserOfSomeClass and call DoSomething().

4. Check that MessageBox.Show() was called during the test with the string "Exception caught: foo".

Code
C#

[TestMethod, Isolated]
public void ComplexTest()
{
  // Arrange
  Isolate.WhenCalled(()=>SomeClass.MyMethod()).WillThrow(new Exception("foo"));
  Isolate.WhenCalled(()=>MessageBox.Show(String.Empty)).WillReturn(DialogResult.Cancel);

  // Act
  UserOfSomeClass user = new UserOfSomeClass();
  user.DoSomething();

  // Assert
  Isolate.Verify.WasCalledWithExactArguments(()=>MessageBox.Show("Exception caught: foo"));
}

public class SomeClass
{
  public static void MyMethod()
  {
    // do work
  }
}

public class UserOfSomeClass()
{
  public void DoSomething()
  {
  try
    {
      SomeClass.MyMethod();
    }
  catch (Exception exc)
    {
      MessageBox.Show("Exception caught: " + exc.Message);
    }
  }
}

VB

<TestMethod(), Isolated()> 
Public Sub ComplexTest()
    ' Arrange
    Isolate.WhenCalled(Sub() SomeClass.MyMethod()).WillThrow(New Exception("foo"))
    Isolate.WhenCalled(Function() MessageBox.Show([String].Empty)).WillReturn(DialogResult.Cancel)

    ' Act
    Dim user As New UserOfSomeClass()
    user.DoSomething()

    ' Assert
    Isolate.Verify.WasCalledWithExactArguments(Function() MessageBox.Show("Exception caught: foo"))
End Sub

Public Class SomeClass
    Public Shared Sub MyMethod()
        ' do work
    End Sub
End Class

Public Class UserOfSomeClass
    Public Sub DoSomething()
        Try
            SomeClass.MyMethod()
        Catch exc As Exception
            MessageBox.Show("Exception caught: " + exc.Message)
        End Try
    End Sub
End Class