Faking Method Chaining

Method chaining is a common syntax for invoking multiple method calls. Each method returns an object that allows the calls to be chained together in a single statement. A method chain causes the increase in the number of methods that come one after another in the same line that occurs as more methods are chained together even though line breaks are often added between methods.

When to Use

When you have a hierarchy of objects and you want to define a specific behavior for a chain of methods.

Syntax

C#

Isolate.WhenCalled(() => <fake>.<method1>.<method2>…).<behavior>;

VB

Isolate.WhenCalled(Function() <fake>.<method1>.<method2>…).<behavior>

Samples

The following sample shows how to fake a complete chain of calls at once by calling them in Isolate.WhenCalled().

When one of the methods in the chain returns an unsupported type (including collections in mscorlib), Typemock Isolator throws an exception.

C#

// Note: Use Isolated to clean up after the test
[TestMethod, Isolated] 
public void SetUpChain_Example()
{
  var fakeDependency = Isolate.Fake.Instance<Dependency>();
  // Note The chain of calls that will be faked
  Isolate.WhenCalled(() => fakeDependency.GetPatent().GetID()).WillReturn(2);
  var result = new ClassUnderTest().AddToChainedDependency(1, fakeDependency);
  Assert.AreEqual(3, result);
}

public int AddToChainedDependency(int a, Dependency dependency)
{
  return a + dependency.GetPatent().GetID();
}

VB

' Note: Use Isolated to clean up after the test
<TestMethod(), Isolated()> 
Public Sub SetUpChain_Example()
     Dim fakeDependency = Isolate.Fake.Instance(Of Dependency)()
     ' Note The chain of calls that will be faked
     Isolate.WhenCalled(Function() fakeDependency.GetPatent().GetID()).WillReturn(2)

     Dim result = New ClassUnderTest().AddToChainedDependency(1, fakeDependency)
     Assert.AreEqual(3, result)
 End Sub

Public Function AddToChainedDependency(a As Integer, dependency As Dependency) As Integer
  Return a + dependency.GetPatent().GetID()
End Function