Testing private method in unit testing

Ideally, it is not recommended to test private methods, as complex internals should be kept hidden and only interface be tested. Well, in real world, sometimes, you need to test your private methods, as it performs very important operation.

In my case, the method was public and later I changed it to private, since it is better to be hidden. Yet, I still wanted to test it, as it does lots of things – calling several other private methods and sum up the result.

You can use .Net reflection and easily do it. One nice article I found by googling was http://www.codeproject.com/KB/cs/testnonpublicmembers.aspx. Simple and straight-forward.

I created a static helper method. I changed variable names in the above example, as it follows old C++ style. These days, C# guys prefer longer variable name without type prefix.

public class TestHelper
{
    public static object RunStaticMethod(Type type, string method, object[] parameters)
    {
        return RunMethod(type, method, null, parameters, BindingFlags.Static | BindingFlags.NonPublic);
    }

    public static object RunInstanceMethod(Type type, string method, object instance, object[] parameters)
    {
        return RunMethod(type, method, instance, parameters, BindingFlags.Instance | BindingFlags.NonPublic);
    }

    private static object RunMethod(Type type, string method, object instance, object[] parameters, BindingFlags flags)
    {
        try
        {
            MethodInfo info = type.GetMethod(method, flags);
            return info.Invoke(instance, parameters);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}
Testing private method in unit testing

Leave a Reply

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