如何访问静态类私有字段以使用Microsoft Fakes in C#对其方法进行单元测试

krr*_*hna 1 c# unit-testing microsoft-fakes

我有下面的静态类和一个方法,我需要进行单元测试.我能够但是这个方法有if条件,它使用一个布尔私有变量,如果它的值为false,那么它执行if条件中的步骤.

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
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)

有没有办法我可以将私有字段bNoError值设置为true,这样我就可以有一个测试方法来测试if条件中的逻辑.

Mar*_*eke 9

出于UnitTesting的目的,Microsoft已经实现了一些帮助类(PrivateTypePrivateObject),这些类使用反射来实现这样的场景.

PrivateType myTypeAccessor = new PrivateType(typeof(TypeToAccess));
myTypeAccessor.SetStaticFieldOrProperty("bNoError", false);
Run Code Online (Sandbox Code Playgroud)

PrivateType用于静态访问,而PrivateObject用于测试实例化对象.

您需要包含Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll中的Microsoft.VisualStudio.TestTools.UnitTesting命名空间才能使用这些命名空间.


ven*_*mit 6

您可以使用反射来执行此操作以进行测试。虽然这很违法。

using System.Reflection;
................
................
var field = typeof(Logger).GetField("bNoError", 
                            BindingFlags.Static | 
                            BindingFlags.NonPublic);

        // Normally the first argument to "SetValue" is the instance
        // of the type but since we are mutating a static field we pass "null"
        field.SetValue(null, false);
Run Code Online (Sandbox Code Playgroud)