Testing Private Methods/Member Variables - Should you or shouldn't you

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:

using

Microsoft.VisualStudio.QualityTools.UnitTesting.Framework;

public

class TestedClass
{
    private bool privateField = true;

    private bool PrivateMethod()
{
return privateField;
    }
}

[TestClass]
public class PrivateTest
{
    private PrivateObject privateObject;

    [TestInitialize]
    public void Initialize()
    {
        TestedClass testedClass = new TestedClass();
        privateObject = new PrivateObject(testedClass);
    }

[TestMethod]
    public void PrivateField()
    {
        bool field = (bool)privateObject.GetField("privateField");
        Assert.IsTrue(field);
    }

    [TestMethod]
    public void PrivateMethod()
    {
        bool result = (bool)privateObject.Invoke("PrivateMethod");
        Assert.IsTrue(result);
    }
}

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.