如何使用 PrivateObject 访问我的类及其父类的私有成员?

发布于 2024-10-25 14:17:40 字数 1629 浏览 2 评论 0原文

我正在测试一个属于层次结构一部分的类。我一直在使用被测对象设置测试类,并设置一个 PrivateObject 以允许访问该对象。当我尝试访问父类的私有成员时,出现异常。

到目前为止,我发现的唯一解决方法是将指定基类的 PrivateType 传递给 PrivateObject 构造函数,但它不适用于子类的私有成员。

有什么方法可以做到这一点,也许通过使用 Private 对象的 Get* 方法上的绑定标志参数?

我确实尝试使用自动生成的访问器类(在主类中右键单击,创建私有访问器)。然而,更糟糕的是:它显示了一个我可以读取的属性,但它抛出了与 PrivateObject 相同的异常,并且我没有其他选项可以使用(绑定标志或诸如此类的东西)来修复异常。

这是我的示例测试代码。我希望有某种方法来构造和使用 PrivateObject 来检索这两个字段。

public class BaseClass
{
    private int one = 1;
}

public class SubClass : BaseClass
{
    private int two = 2;
}

[TestClass]
public class UnitTest1
{
    BindingFlags flags = BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;

    [TestMethod]
    public void TestMethod1()
    {
        SubClass test = new SubClass();
        PrivateObject priv = new PrivateObject(test);

        Assert.AreNotEqual<int>(0, (int)priv.GetFieldOrProperty("one", flags)); // System.MissingMethodException: Method 'PrivateObjectTester.SubClass.one' not found.
        Assert.AreNotEqual<int>(0, (int)priv.GetFieldOrProperty("two", flags));
    }

    [TestMethod]
    public void TestMethod2()
    {
        SubClass test = new SubClass();
        PrivateObject priv = new PrivateObject(test, new PrivateType(typeof(BaseClass)));

        Assert.AreNotEqual<int>(0, (int)priv.GetFieldOrProperty("one", flags));
        Assert.AreNotEqual<int>(0, (int)priv.GetFieldOrProperty("two", flags)); // System.MissingMethodException: Method 'PrivateObjectTester.BaseClass.two' not found.
    }
}

I'm testing a class that is part of a hierarchy. I've been setting up my test classes with the object under test, and a PrivateObject to allow access to that object. I'm getting exceptions when I attempt to access private members of the parent class.

The only workaround I've found so far is to pass a PrivateType specifying the base class to the PrivateObject constructor, but then it doesn't work on private members of the subclass.

Is there some way I can do this, perhaps by using the binding flags parameter on the Get* methods of Private object?

I did try using the automatically-generated Accessor classes (right-click in the main class, Create Private Accessor). However, that's worse: It shows a property I can read, but it throws the same exception as PrivateObject does, and there's no other options I can use (binding flags or whatnot) to fix the exception.

Here's my sample test code. I'd like there to be some way to construct and use the PrivateObject to retrieve both fields.

public class BaseClass
{
    private int one = 1;
}

public class SubClass : BaseClass
{
    private int two = 2;
}

[TestClass]
public class UnitTest1
{
    BindingFlags flags = BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;

    [TestMethod]
    public void TestMethod1()
    {
        SubClass test = new SubClass();
        PrivateObject priv = new PrivateObject(test);

        Assert.AreNotEqual<int>(0, (int)priv.GetFieldOrProperty("one", flags)); // System.MissingMethodException: Method 'PrivateObjectTester.SubClass.one' not found.
        Assert.AreNotEqual<int>(0, (int)priv.GetFieldOrProperty("two", flags));
    }

    [TestMethod]
    public void TestMethod2()
    {
        SubClass test = new SubClass();
        PrivateObject priv = new PrivateObject(test, new PrivateType(typeof(BaseClass)));

        Assert.AreNotEqual<int>(0, (int)priv.GetFieldOrProperty("one", flags));
        Assert.AreNotEqual<int>(0, (int)priv.GetFieldOrProperty("two", flags)); // System.MissingMethodException: Method 'PrivateObjectTester.BaseClass.two' not found.
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

旧城空念 2024-11-01 14:17:40

我没有找到答案,所以这就是我最终所做的。我为类层次结构的每一层创建了PrivateObjects,并且在编写测试用例时我只需要小心并使用正确的用例即可。

public class BaseClass
{
    private int one = 1;
}

public class SubClass : BaseClass
{
    private int two = 2;
}

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod()
    {
        SubClass test = new SubClass();
        PrivateObject privSub = new PrivateObject(test, new PrivateType(typeof(SubClass)));
        PrivateObject privBase = new PrivateObject(test, new PrivateType(typeof(BaseClass)));

        Assert.AreNotEqual<int>(0, (int)privBase.GetFieldOrProperty("one"));
        Assert.AreNotEqual<int>(0, (int)privSub.GetFieldOrProperty("two"));
    }
}

I didn't find the answer, so this is what I ended up doing. I created PrivateObjects for each level of the class's hierarchy, and I just need to be careful when writing test cases that I use the proper one.

public class BaseClass
{
    private int one = 1;
}

public class SubClass : BaseClass
{
    private int two = 2;
}

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod()
    {
        SubClass test = new SubClass();
        PrivateObject privSub = new PrivateObject(test, new PrivateType(typeof(SubClass)));
        PrivateObject privBase = new PrivateObject(test, new PrivateType(typeof(BaseClass)));

        Assert.AreNotEqual<int>(0, (int)privBase.GetFieldOrProperty("one"));
        Assert.AreNotEqual<int>(0, (int)privSub.GetFieldOrProperty("two"));
    }
}
草莓味的萝莉 2024-11-01 14:17:40

这可能不是您想要的答案......但您不应该首先在一个方法中测试这两个类。您一次应该只测试一门课程。如果您觉得有必要这样做,那么我猜您的代码需要重构。但由于我不知道你现实生活中的代码问题,我不能肯定地说

This likely isn't the answer you want...but you shouldn't be testing both classes in one method in the first place. You should only ever be testing one class at a time. If you feel the need to do this, then I'd guess that your code needs refactoring. But as I don't know your real-life code problem, I can't say for sure

雪化雨蝶 2024-11-01 14:17:40

我想做同样的事情,我做了这个扩展方法。现在效果很好。我最初的想法来自你的帖子。谢谢你!

https://github.com/cactuaroid/PrivateObjectExtensions

它所做的基本上是通过 查找成员所有者递归地调用 Type.GetFields()Type.GetProperties(),然后创建 PrivateObject(或 PrivateType)作为正确的类型来访问成员。

I wanted to do same thing and I made this extension methods. Now it works well. My initial idea is from your post. Thank you!

https://github.com/cactuaroid/PrivateObjectExtensions

What it's doing basically is finding member owner by Type.GetFields() and Type.GetProperties() recursively, and then create PrivateObject (or PrivateType) as correct type to access the member.

梦与时光遇 2024-11-01 14:17:40

使用 PrivateType 指定所需的类型并使用 PrivateObject 的不同构造函数:

var test = new SubClass();
var privateType = new PrivateType(typeof(BaseClass));
var privateObject = new PrivateObject(test, privateType);
// privateObject.GetFieldOrProperty("one", flags)

Use PrivateType to specify the desired type and use a different constructor of PrivateObject:

var test = new SubClass();
var privateType = new PrivateType(typeof(BaseClass));
var privateObject = new PrivateObject(test, privateType);
// privateObject.GetFieldOrProperty("one", flags)
烟花肆意 2024-11-01 14:17:40

PrivateObject 在处理继承方面有点“愚蠢”。不幸的是,它的方法不是虚拟的,因此没有简单的方法来改变这种行为。您基本上有两个选择:要么接受限制,要么创建自己的私有访问器助手,可以透明地处理继承的成员。

PrivateObject is a bit on the "dumb" side when it comes to handling inheritance. Unfortunately, its methods are not virtual, so there's no easy way to change this behaviour. You essentially have two options: either live with the limitations or create your own private accessor helper that can handle inherited members transparently.

拥抱没勇气 2024-11-01 14:17:40
// create an instance of class SearchPlanogramsBuilder:
SearchPlanogramsBuilder searchPlanogramBuilder = new SearchPlanogramsBuilder(); 

// executing the method BuildSearchParameters(return type is void) with input searchPlanoGramsFilters:
searchPlanogramBuilder.BuildSearchParameters(searchPlanoGramsFilters);

// create privateobject and pass instance created for the class:
PrivateObject helperobject1 = new PrivateObject(searchPlanogramBuilder);

// type cast exactly as parameter(which is private variable) in the method:
Collection<string> parameter = (Collection<string>)helperobject1.GetFieldOrProperty("parameters");
// create an instance of class SearchPlanogramsBuilder:
SearchPlanogramsBuilder searchPlanogramBuilder = new SearchPlanogramsBuilder(); 

// executing the method BuildSearchParameters(return type is void) with input searchPlanoGramsFilters:
searchPlanogramBuilder.BuildSearchParameters(searchPlanoGramsFilters);

// create privateobject and pass instance created for the class:
PrivateObject helperobject1 = new PrivateObject(searchPlanogramBuilder);

// type cast exactly as parameter(which is private variable) in the method:
Collection<string> parameter = (Collection<string>)helperobject1.GetFieldOrProperty("parameters");
戈亓 2024-11-01 14:17:40

正如安德烈·佩纳所写。为什么要通过子类测试基类的私有成员。您也无法在子类的正常代码中访问这些成员。您必须使属性成员受保护才能从子类访问它们。

然后您还可以使用 PrivateObject 测试这些成员。

As André Pena wrote. Why would you like to test private members of the Baseclass through the Subclass. You wouldn't have access to these members in normal code of your Subclass either. You have to make the Properties members protected to have access to them from the Subclass.

Then you can also test these Members with the PrivateObject.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文