Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PrivateObject does not find property

I have a structure which looks basicly like this:

abstract class A
{
   protected string Identificator { get; set; }

   private void DoSomething()
   {

       // ...

       DoSomethingSpecific();
   }

   protected abstract void DoSomethingSpecific();
}

Because of the complexity I need do unit tests the DoSomething method to be sure it works allways in the same way. Thats why I created following stub.

public class AStub : A
{
    protected override void DoSomethingSpecific()
    {
        // nothing to do
    }
}

I use the PrivateObject class to access the methods and properties of class A be instantiating class AStub. This worked for a while and for some reason crashes now whenever I try to access either the property or the method.

following code for testing:

var sut = new CommonIodAdapterImpl();
var accessor = new PrivateObject(sut);

accessor.SetProperty("Identificator", "blablub");
accessor.Invoke("DoSomething", null);

// assert...

The exception which is thrown is a MissingMethodException telling me that the propertie or method was not found. But when I debug and check the hierachy every seems to be right inclduing the spelling.

Thank you for your help.

like image 792
HerrLoesch Avatar asked Dec 13 '22 16:12

HerrLoesch


2 Answers

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)));
like image 50
Rob Sedgwick Avatar answered Dec 30 '22 04:12

Rob Sedgwick


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.

like image 39
TToni Avatar answered Dec 30 '22 05:12

TToni