Faking Static Constructors

By default, Typemock Isolator does not fake the static constructor. When a type is created or faked, or a static method is called, the static constructor is invoked only once by the CLR.

When to Use

When you want to fake the static constructor of a type.

Typemock Isolator forces a call of the original static constructor when running a test which does not fake the static constructor.

Syntax
C#

// Fake the static constructor
Isolate.Fake.StaticConstructor<Dependency>();

VB

' Fake the static constructor
Isolate.Fake.StaticConstructor(Of Dependency)()

Because different runners might run tests in a different order, it is not possible to control calls of the static constructor unless the static constructor is explicitly called in every test. It is recommended to either call or fake the static constructor in every test.

Faking an instance might cause calling the static constructor if this is the first time the type is called. To suspend the static call, use Isolate.Fake.StaticConstructor() explicitly before calling Isloate.Fake.Instance().

Samples
C#

[TestMethod, Isolated]
public void FakingStaticConstructor()
{
  Isolate.Fake.StaticConstructor<StaticConstructorExample>();

  // calling a static method on the class forces the static constructor to be called
  StaticConstructorExample.Foo();

  // this verifies the static constructor was faked and not called
  Assert.IsFalse(StaticConstructorExample.TrueOnStaticConstructor);
}

public class StaticConstructorExample
{
  private static bool trueOnStaticConstructor = false;

  public static bool TrueOnStaticConstructor
  {
    get { return trueOnStaticConstructor; }
    set { trueOnStaticConstructor = value; }
  }

  static StaticConstructorExample()
  {
    trueOnStaticConstructor = true;
  }

  public static void Foo()
  {
  }
}

VB

<TestMethod(), Isolated()> _
Public Sub FakingStaticConstructor()
  Isolate.Fake.StaticConstructor(Of StaticConstructorExample)()

  ' calling a static method on the class forces the static constructor to be called
  StaticConstructorExample.Foo()

  ' this verifies the static constructor was faked and not called
  Assert.IsFalse(StaticConstructorExample.TrueOnStaticConstructor)
End Sub

Public Class StaticConstructorExample
  Private Shared m_trueOnStaticConstructor As Boolean = False

  Public Shared Property TrueOnStaticConstructor() As Boolean
    Get
      Return m_trueOnStaticConstructor
    End Get
    Set(value As Boolean)
      m_trueOnStaticConstructor = value
    End Set
  End Property

  Shared Sub New()
    m_trueOnStaticConstructor = True
  End Sub

  Public Shared Sub Foo()
  End Sub
End Class