Given you have an abstract base class with non-public member, and a derived class with other non-public member too. Now you want to unit-test some of the non-public member (methods) of the derived class.
Prior the call of the method of the derived class, you need to set some non-public properties declared in the base class.
The problem I ran into was, that, using the derived class’ accessor, I was not able to access the properties of the base class. But without setting them, I can’t test the method.
The solution is somewhat uncommon, but it works. You need two private accessors, ‘pointing’ to the same object. Use the one to manipulate the base class’ member, and the other to access the derived class’ member. Since both accessors point to the same object, you do access that single object. See the code below:
DerivedClass instance = new DerivedClass(); BaseClass_Accessor baseAccessor = new BaseClass_Accessor(new PrivateObject(instance, new PrivateType(typeof(DerivedClass)))); baseAccessor.ProtectedProperty = someValue; DerivedClass_Accessor accessor = new DerivedClass_Accessor(new PrivateObject(instance)); accessor.CallMethodToTest();