Verifying the Number of Times a Method Was Called

You might want to count how many times a method was called. While using Isolate.Verify.<Verification_Statement> passes for at least one call, it might be useful to know the exact number of calls made.

To get the number of calls to a method, use Isolate.Verify.GetTimesCalled().

When to Use

When the number of times a specific method is called is important for the test.

Do not overuse this feature because it might make your test brittle.

Syntax

C#

int count = Isolate.Verify.GetTimesCalled(() => <method>);

VB

int count = Isolate.Verify.GetTimesCalled(Function() <method>)

Samples

The following sample shows how to get the number of times that fakeBag.AddItem() was called.

Use Verify.GetTimesCalled() to count calls on any public instance or static methods.

Verify.GetTimesCalled() returns total call count, regardless of the arguments.

C#

[TestMethod, Isolated]
public void GetTimesCalledExample_FillBag()
{
  var fakeBag = Isolate.Fake.Instance<Bag>();
  var thief = new Shoplifter();
  thief.FillBag(fakeBag);
  int count = Isolate.Verify.GetTimesCalled(() => fakeBag.AddItem(""));
  Assert.AreEqual(2, count);
}

public class Shoplifter
{
  public void FillBag(Bag bag)
  {
    bag.AddItem("Stolen Watch");
    bag.AddItem("Stolen Necklace");
  }
}

VB

<TestMethod, Isolated>
Public Sub GetTimesCalledExample_FillBag()
    Dim fakeBag = Isolate.Fake.Instance(Of Bag)()
    Dim thief = New Shoplifter()
    thief.FillBag(fakeBag)
    Dim count As Integer = Isolate.Verify.GetTimesCalled(Function() fakeBag.AddItem(""))
    Assert.AreEqual(2, count)
End Sub

Public Class Shoplifter
    Public Sub FillBag(bag As Bag)
        bag.AddItem("Stolen Watch")
        bag.AddItem("Stolen Necklace")
    End Sub
End Class