I have a unit test for a method which gets an object from a collection. This keeps failing and I cannot see why, so I have created a very simple test below to create 2 suppl
//Given the following structure and an instance value, targetObj...
class BaseType
{
private FeatureType Feature_1;
}
class TargetType : BaseType
{
...
}
TargetType targetObj = new TargetType();
//...a private feature in a specific base class can be accessed as follows
PrivateType typeCast = new PrivateType(typeof( BaseType ));
PrivateObject privateObj = new PrivateObject(targetObj, typeCast);
//...and values can be retrieved and set as follows....
privateObj.SetField("Feature_1", (FeatureType) newValue );
FeatureType result = (FeatureType) privateObj.GetField("Feature_1");
/* With respect to the controversy around accessing private fields in unit tests, I believe it should never be used unless absolutely neccessary (i.e. time and expense management issues). */