One of the often requested features of NUnit was the ability to test private member variables and private methods. I resisted because I always felt that if you limited yourself to the public interface that enabled you to freely change the implementation without having to change the tests. This I believe is a good thing because if the tests require a lot of maintenance you might be tempted to not do it. However, the flip side of the equation is you may end up exposing a method or worse yet a member variable only for testability. The downside of this is that once it is present in the interface it could be used for something else. So, as usual there are arguments on either side.
.NET, through reflection, provides the ability to invoke private methods and see the values of private member variables so it is not impossible to do this even today. However, the unit testing tool in VS Team System has a built-in wrapper, called PrivateObject, to make the syntax a bit easier to digest.
Here is an example:
private bool privateField = true;
private bool PrivateMethod()
public class PrivateTest
private PrivateObject privateObject;
public void Initialize()
TestedClass testedClass = new TestedClass();
privateObject = new PrivateObject(testedClass);
public void PrivateField()
bool field = (bool)privateObject.GetField(“privateField”);
public void PrivateMethod()
bool result = (bool)privateObject.Invoke(“PrivateMethod”);
As with all capabilities there is a right time and a wrong time to use them. I will be spending more time on this over the next few weeks but I would really like to get your feedback about this and recommendations on practice.
This posting is provided “AS IS” with no warranties, and confers no rights.