繁体   English   中英

重载构造函数C#单元测试的Class中的私有成员

[英]private members in Class with overload constructor C# Unit Test

如何在单元测试中访问私有成员? 我尝试使用PrivateObject,但是重载构造函数在这里,我收到_inkContainerValue的错误。 我可以在不使用类对象的情况下获得私有成员的访问权限吗?

  public class Pen
   {

    private int _inkContainerValue = 1000;

    #region Constructors

    public Pen(int inkContainerValue)
    {
        this._inkContainerValue = inkContainerValue;
    }

    #endregion
    }

}

PrivateObject pObj = new PrivateObject(typeof(Pen));
int privateInkContainerValue = (int)pObj.GetField("_inkContainerValue");

尝试上面的代码通过单元测试中的PrivateObject类获取_inkContainerValue字段的值。

// Following is overloaded version to pass value to actual Pen class's constructor.
PrivateObject pObj = new PrivateObject(typeof(Pen), new object[]{12});
int privateInkContainerValue = (int)pObj.GetField("_inkContainerValue");

我现在没有编辑。 语法应该理想地工作。

我可以在不使用类对象的情况下获得私有成员的访问权限吗?

不。您必须具有一个对象实例才能从该对象中提取数据。

没有冒犯,但是由于构造函数重载而对使用Reflection的犹豫似乎没有意义。 如果有一个实例,它不会阻止您使用反射;如果没有,则不能创建一个实例。

这是一个使用Reflection从_ink获取值的_ink 它还显示了如何在不使用构造函数的情况下获取实例。 但是,请记住, 不会初始化任何内容。 _ink将为0而不是您在代码中看到的1000

public class Pen
{
    int _ink = 1000;

    public Pen(int ink)
    {
        _ink = ink;
    }
}

void Test()
{
    //Create the object and check constructor set the value
    var pen = new Pen(5);
    var field = pen.GetType().GetField("_ink", BindingFlags.NonPublic|BindingFlags.Instance);

    // This should pass.
    Debug.Assert((int)field.GetValue(pen) == 5);

    // Create the pen without using constructor. 
    // No matter what, nothing is initialized meaning _ink is 0 and not 1000.
    // Hence, uninitialized.
    var uninitializedPen = (Pen)FormatterServices.GetUninitializedObject(typeof(Pen));
    field = uninitializedPen.GetType().GetField("_ink", BindingFlags.NonPublic|BindingFlags.Instance);

    //This will fail.
    Debug.Assert((int)field.GetValue(uninitializedPen) == 1000);
}

为了使用FormatterServices类,您需要导入System.Runtime.Serialization命名空间。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM