PrivateObject does not find property

百般思念 提交于 2019-12-05 12:20:34

You need to set the PrivateType argument to your base class to access the private members at that level.

var accessor = new PrivateObject(sut, new PrivateType(typeof(A)));

Shouldn't that be "public class AStub : A"?

To resolve the missing method exception just compile everything(!) once more. Either you get some compiler error telling you what's wrong or the error will vanish.

If it still doesn't work, check if you don't have multiple copies of the assemblies (including GAC!) and watch in the Deboug-Out-Window if it loads the assemblies from the correct path.

I just tried something similar, i assmued it's because the property is protected rather than private.

I created my own accessor in my test assembly

public class AAccessor : A
{
    // use this instead of Identificator
    public string IdentificatorAccessor 
    {
        get { return this.Identificator; }
        set { this.Identificator = value; }
    }

    // test this method in your unit test
    public void DoSomethingAccessor()
    {
        this.DoSomethingSpecific()
    }

    // need this to satisfy the abstract class
    protected override void DoSomethingSpecific()
    {
        // do nothing here
    }
}
public class BaseClass
{
   private int _fieldToSet;
   ...
}

public class DerivedClass : BaseClass
{
   ...
}

// Unit Test Code

public void Test()
{
   DerivedClass d = new DerivedClass();
   PrivateObject privObj = new PrivateObject(d, new PrivateType(typeof(BaseClass));
   privObj.SetFieldOrProperty("fieldToSet", 8675309);
   ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!