Simulating Error in Constructor

When to Use

When you want to test a failure that occurs when constructing an object. For example, an OutOfMemoryException.

Syntax
C#

Isolate.Swap.NextInstance<Dependency>().ConstructorWillThrow(new OutOfMemoryException());

VB

Isolate.Swap.NextInstance(Of Dependency)().ConstructorWillThrow(New OutOfMemoryException())

Samples

The following sample shows how to fake an exception that is thrown when an object is created.

C#

[TestMethod, Isolated]
public void FutureInstance_VerifyThrowingExceptionOnCreation()
{
  // We want a memory handling exception to be thrown the next time a Dependency is instantiated
  Isolate.Swap.NextInstance<Dependency>().ConstructorWillThrow(new OutOfMemoryException());
  var classUnderTest = new ClassUnderTest();
  var result = classUnderTest.Create();
  Assert.AreEqual(null, result);
}

public class ClassUnderTest
{
  public Dependency Create()
  {
    try
    {
      return new Dependency(0, "");
    }
    catch (Exception)
    {
      return null;
    }
  }
}

public class Dependency
{
  public int Age;
  public string Name;

  public Dependency(int age, string name)
  {
    Age = age;
    Name = name;
  }
}

VB

<TestMethod(), Isolated()>_
Public Sub FutureInstance_VerifyThrowingExceptionOnCreation()
  ' We want a memory handling exception to be thrown the next time a Dependency is instantiated
  Isolate.Swap.NextInstance(Of Dependency)().ConstructorWillThrow(New OutOfMemoryException())
  Dim result = New ClassUnderTest().Create()
  Assert.AreEqual(Nothing, result)
End Sub

Public Class ClassUnderTest
  Public Function Create() As Dependency
    Try
      Return New Dependency(0, "")
    Catch generatedExceptionName As Exception
      Return Nothing
    End Try
  End Function
End Class

Public Class Dependency
  Public Age As Integer
  Public Name As String
  
  Public Sub New(age__1 As Integer, name__2 As String)
    Age = age__1
    Name = name__2
  End Sub
End Class