Faking Future Instances

In many cases, there is no clear way to pass fake objects into the code under test. In some cases, the code under test instantiates an object that you need to fake (that is a future instance). With Typemock Isolator, you can fake these instances in your unit test.

When to Use

When you want to fake the object that was created within the method under test.

Syntax

C#

var handle = Isolate.Fake.NextInstance<T>();

VB

Dim handle = Isolate.Fake.NextInstance(Of T)()

To fake a specific amount of future instances, use Isolate.Fake.NextInstance() sequentially.

Isolate.Fake.NextInstance() works with interface or abstract classes too. The next object that implements the interface or derives from the abstract class will be faked.

Samples

The following sample shows how to fake a future instance of Dependency.

C#

[TestMethod, Isolated]
public void Fake_FutureInstance()
{
  var handle = Isolate.Fake.NextInstance<Dependency>();

  var result = ClassUnderTest.AddSecurly(1, 2);

  Assert.AreEqual(3, result);
}
 
public static int AddSecurly(int x, int y)
{
  var dependency = new Dependency();
  dependency.Check();

  return x + y;
}
 
public class Dependency
{
  public void Check()
  {
    throw new Exception("No Entry");
  }
}

VB

<TestMethod(), Isolated()> _
Public Sub Fake_FutureInstance()
  
  Dim handle = Isolate.Fake.NextInstance(Of Dependency)()

  Dim result = ClassUnderTest.AddSecurly(1, 2)

  Assert.AreEqual(3, result)
End Sub
 
Public Shared Function AddSecurly(x As Integer, y As Integer) As Integer
  Dim dependency = New Dependency()
  dependency.Check()

  Return x + y
End Function
 
Public Class Dependency
  Public Sub Check()
    Throw New Exception("No Entry")
  End Sub
End Class

Verifying is done on the instance returned from Isolate.Fake.NextInstance.

Use Isolate.Verify.GetInstancesOf to get the future instance, this can be used for Argument Validations and field Assertions.

Isolator doesn't allow calling methods of the handle directly.