Faking Future Instances of Non-Visible Type
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 and it's hidden object type.
Syntax
C# var handle = Isolate.Fake.NextInstance(type);
VB
Dim handle = Isolate.Fake.NextInstance(type)
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.
Resulting Fake in the test will have type 'object'. For setting behavior on it use Isolate.NonPublic API or by casting to visible base class if this is permissible.
Samples
The following sample shows how to fake a future instance of NotVisibleTypeToFake.
C# [TestMethod, Isolated] public void FakingFutureInstanceOfNotVisibleType() { //Arrange var internalType = typeof(VisibleType).Assembly.GetType("ThirdPartyProject.NotVisibleTypeToFake"); Isolate.Fake.NextInstance(internalType); //Act var result = new VisibleType().Calculate(5); //Assert Assert.AreEqual(25, result); } public class VisibleType { public int Calculate(int i) { new NotVisibleTypeToFake().Check(); return i * i; } } internal class NotVisibleTypeToFake { public void Check() { throw new Exception("No Entry"); } }
VB <TestMethod(), Isolated()> _ Public Sub FakingFutureInstanceOfNotVisibleType() 'Arrange Dim internalType = GetType(VisibleType).Assembly.GetType("ThirdPartyProject.NotVisibleTypeToFake") Isolate.Fake.NextInstance(internalType) 'Act Dim result = New VisibleType().Calculate(5) 'Assert Assert.AreEqual(25, result) End Sub Public Class VisibleType Public Function Calculate(i As Integer) As Integer Call New NotVisibleTypeToFake().Check() Return i * i End Function End Class Friend Class NotVisibleTypeToFake 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.