[Code snippet] How to set value of private variable in Unit Test Using Reflection ?

A sample example to set private variable to true from unit test class in C#.Net

//TestService.cs
public class TestService
{
        private bool _isInitialized = false;
}



//TestServiceUnitTest.cs
using System.Reflection;

public class TestServiceUnitTest
{
          private TestService _testService;
       
           [TestInitalize]
          private void testInitalize()
         {
            _testService = new TestService();
         }
       
         [TestMethod]
         Private void SetInitializeToTrue()
         {
                         FieldInfo field = typeof(TestService).GetField("_isInitialized",  BindingFlags.NonPublic |       BindingFlags.Instance);

          field.SetValue(_testService , true);

         }
}

Comments

Popular posts from this blog

Generate ArcGIS Token By URL Request From ArcGIS Portal, Federated Environment , ESRI JS API and Angular snippets

Update WPF Interaction Triggers in from .Net Framework 4.8 to .Net 5

Solution: IntelliJ not recognizing a particular file correctly, instead its stuck as a text file