Unit Test Private Methods in Abstract Classes

I was sharing what I’d learned about unit testing private methods with some co-workers, and the idea of testing a private method of an abstract class was presented.

PrivateObject deals with this handily by allowing you to specify the type being tested in one of its constructors.

Here’s a simple example. Consider we have an abstract class, Mammal, and a derived class, Human.

public abstract class Mammal
{
    private void SecretMammalStuff()
    {
    }
}

public class Human : Mammal
{
}

We can test Mammal’s private method by doing the following:

var human = new Human();
var po = new PrivateObject(human, new PrivateType(typeof(Mammal)));
po.Invoke("SecretMammalStuff");

If we don’t specify the PrivateType argument in the PrivateObject constructor, we’re not able to access the base class’s private methods. This is the key to testing private methods in an abstract class.

Advertisements

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s