Unit testing private methods with PrivateObject and PrivateType

There are a lot of discussions in the Internet about the sense of testing the code with private accessors. In my opinion all of the discussions coming from the wrong understanding of the topic.

What is unit testing? It is a testing of units, not classes, not methods exposed by some API. The term private is supposed to be private to the consumer, not to unit tests. In here it is worth t mention that in most cases private methods will be tested and code coverage will present those parts of code as covered, if you properly test public methods which are invoking at some point the private code.

But let's image the situation when we have some private method in our class and want to create a unit test for it..

public class Calculator
{
    private int Add(int x, int y)
    {
        return x + y;
    }

    private static int Multiply(int x, int y)
    {
        return x * y;
    }
}

[TestMethod]
public void TestPrivateMethod()
{
    Calculator calculator = new Calculator();
    PrivateObject privateObject = new PrivateObject(calculator);

    int x = 2;
    int y = 3;
    const int expected = 5;
    int actual = (int)privateObject.Invoke("Add", x, y);   

    Assert.AreEqual(expected, actual);
}

[TestMethod]
public void TestPrivateStaticMethod()
{
    PrivateType privateType = new PrivateType(typeof(Calculator));

    int x = 2;
    int y = 3;
    const int expected = 6;
    int actual = (int)privateType.InvokeStatic("Multiply", x, y);

    Assert.AreEqual(expected, actual);
}

Pretty similar to reflection, isn't it? I've used in here the PrivateObject class. It allows to test methods and properties which are inaccessible because they are not public.

The second test is using PrivateType class. It represents the type of a private class that gives access to private static implementations, so basically you can test private static methods with no problems.

Back to main page

blog comments powered by Disqus