Creating an Object with Private Constructor Creating an Object with Private Constructor Creating an Object with Private Constructor Creating an Object with Private Constructor Creating an Object with Private Constructor Creating an Object with Private Constructor Creating an Object with Private Constructor Creating an Object with Private Constructor Creating an Object with Private Constructor Creating an Object with Private Constructor Creating an Object with Private Constructor Creating an Object with Private Constructor Creating an Object with Private Constructor Creating an Object with Private Constructor Creating an Object with Private Constructor Creating an Object with Private Constructor Creating an Object with Private Constructor Creating an Object with Private Constructor Creating an Object with Private Constructor Creating an Object with Private Constructor Creating an Object with Private Constructor Creating an Object with Private Constructor

Creating an Object with Private Constructor

Using the Non-Public API, you can create a real object despite the fact that the type or its constructor isn't visible

When to Use

When you need to create a real object to test, which constructor is not visible or the type is not visible

if using non-generic API resulting instance 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.

Syntax

C#

Isolate.NonPublic.CreateInstance<Class>();
Isolate.NonPublic.CreateInstance(type);

VB

Isolate.NonPublic.CreateInstance(Of Class)()
Isolate.NonPublic.CreateInstance(type)

Sample

C#

public class ClassUnderTest
{
  public bool ConstructorWasCalled = false;

  private ClassUnderTest()
  {
    ConstructorWasCalled = true;
  }
}

[TestMethod]
public void CreateInstanceWithPrivateCounstructor()
{
  var fake = Isolate.NonPublic.CreateInstance<ClassUnderTest>();

  Assert.IsTrue(fake.ConstructorWasCalled);
}  

VB

Public Class ClassUnderTest
    Public ConstructorWasCalled As Boolean = False

    Private Sub New()
        ConstructorWasCalled = True
    End Sub
End Class

<TestMethod(), Isolated()>
Public Sub CreateInstanceWithPrivateCounstructor()
        Dim fake = Isolate.NonPublic.CreateInstance(Of ClassUnderTest)()

        Assert.IsTrue(fake.ConstructorWasCalled)
    End Sub