Thursday, July 7, 2011

Unit Testing Private Methods

Sometimes you want to write a unit test against a private method. 

First let me say that most of the time this is an indication of a design problem.  Rather consider whether your class really wants to be more than one class or whether you should be testing the code indirectly using one of the other public methods of the class.

If you are convinced you really want to write a unit test for the private method, there is an alternative to calling the method using AsDynamic ().  The problem with AsDynamic () is that you lose all the benefits of strong typing, including support for refactoring.

Lets say you have a class called Class1 like this:

public class Class1
{
    private void Method1 ()
    {
    }
}

In order to call Method1 you can change Method1 in Class1 to protected and create a testing subclass like this:

public class TestClass1
    : Class1
{
    public void TestMethod1 ()
    {
        Method1 ();
    }
}

In your tests you can then create an instance of TestClass1 and call TestMethod1.

No comments:

Post a Comment