Faking Private Static Fields
Using the Non-Public API you can control non-private static fields of the class
When to Use
When you want to get or set private static field of the class.
Syntax
C# //To get static field var value = Isolate.NonPublic.StaticField<ClassUnderTest>("StaticField").Value; //To set static field Isolate.NonPublic.StaticField<ClassUnderTest>("StaticField").Value = value;
VB
'To get static field
Dim value = Isolate.NonPublic.StaticField(Of ClassUnderTest)("StaticField").Value
'To set static field
Isolate.NonPublic.StaticField(Of ClassUnderTest)("StaticField").Value = value
Sample
C# public class ClassUnderTest { private static int StaticField; public static void Init() { StaticField = 100; } } [TestInitialize] public void Setup() { ClassUnderTest.Init(); } [TestMethod, Isolated] public void GetPrivateStaticField() { //Act var result = Isolate.NonPublic.StaticField<ClassUnderTest>("StaticField").Value; //Assert Assert.AreEqual(100, result); } [TestMethod, Isolated] public void SetPrivateStaticField() { //Arrange Isolate.NonPublic.StaticField<ClassUnderTest>("StaticField").Value = 0; //Act var result = Isolate.NonPublic.StaticField<ClassUnderTest>("StaticField").Value; //Assert Assert.AreEqual(0, result); }
VB
Public Class ClassUnderTest
Private Shared StaticField As Integer
Public Shared Sub Init()
StaticField = 100
End Sub
End Class
<TestInitialize>
Public Sub Setup()
ClassUnderTest.Init()
End Sub
<TestMethod, Isolated>
Public Sub GetPrivateStaticField()
'Act
Dim result = Isolate.NonPublic.StaticField(Of ClassUnderTest)("StaticField").Value
'Assert
Assert.AreEqual(100, result)
End Sub
<TestMethod, Isolated>
Public Sub SetPrivateStaticField()
'Arrange
Isolate.NonPublic.StaticField(Of ClassUnderTest)("StaticField").Value = 0
'Act
Dim result = Isolate.NonPublic.StaticField(Of ClassUnderTest)("StaticField").Value
'Assert
Assert.AreEqual(0, result)
End Sub