Search code examples
c#unit-testingmicrosoft-fakes

How to access a Static Class Private fields to unit test its methods using Microsoft Fakes in C#


I have the below static class and a method in it which I need to unit test. I am able to But this method has the if condition which uses a Boolean private variable and if the value of it is false then it executes the steps in that if condition.

public static class Logger
{
    private static bool bNoError = true;
    public static void Log()
    {
        if (!bNoError)
        {
            //Then execute the logic here
        }
        else
        {
            //else condition logic here
        }
    }
} 

Is there a way I can set the private field bNoError value to true so that I can have one test method which tests the logic in if condition.


Solution

  • For UnitTesting purposes, Microsoft has implemented a few helper classes (PrivateType and PrivateObject) that use reflection for scenarios like this.

    PrivateType myTypeAccessor = new PrivateType(typeof(TypeToAccess));
    myTypeAccessor.SetStaticFieldOrProperty("bNoError", false);
    

    PrivateType is intended for static access, whereas PrivateObject is for testing against instantiated objects instead.

    You will need to include the Microsoft.VisualStudio.TestTools.UnitTesting namespace from the Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll in order to use these.