Monday, May 11, 2020

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

Be The First To Comment
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);

         }
}
 

© 2011 GIS and Remote Sensing Tools, Tips and more .. ToS | Privacy Policy | Sitemap

About Me