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.

Unknown's avatar

Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

Leave a comment