Unit Testing Private Methods

Some very smart and experienced people say not to test private methods. Fair enough. The reasons are good – read here.

This post is not going to buy into that debate. It’s purpose is to demonstrate how to test private methods. The answer is painfully obvious – use reflection.

In my StringExtensions class, I have a private static helper method called GetIndexOfNthCharHelper. I wanted to unit test it (hey it’s my API and I can control it, so some of the Just Say No reasons go away). This is the test I wrote:

public void GetIndexOfNthCharHelperDoes()
	//  Arrange
	var type = typeof (StringExtensions);
	var getIndexOfNthCharHelperMethod = type.GetMethod("GetIndexOfNthCharHelper", BindingFlags.NonPublic | BindingFlags.Static);

	//  Act
	int index = (int)getIndexOfNthCharHelperMethod.Invoke(null, new object[] { path, 2, 0, Path.DirectorySeparatorChar });

	//  Assert                        
	Assert.AreEqual(15, index);

Not too complex. But I do heed the warnings of others and definitely wouldn’t be too keen to unit test a private method of a 3rd party API over which I have no control.

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>