Posted by: joachimvandenbogaert | April 28, 2008

Unit testing private methods

I was wondering whether it was possible to unit test private methods. I googled up some articels about it.

The main tendency was that it is not encouraged:

http://weblogs.asp.net/tgraham/archive/2003/12/31/46984.aspx

This blog presents a workaround by adding a public wrapper for the private method inside debugging code.

http://geekswithblogs.net/geekusconlivus/archive/2006/07/13/85088.aspx

This article shows you how to do things more neatly by using reflection in .NET:

http://www.personalmicrocosms.com/Pages/dotnettips.aspx?c=22&t=25

Although I agree that unit tests are a great help in driving your design, and make you program against an interface instead of against an implementation, I also find it useful to be able to test (as an exception) some smaller methods. Never say never.

On the other hand, I eventually found out that the private method I was writing, could be useful for other classes too. I ended up including the private method in a utility library. Seems like there is a reason for not unit testing private methods after all.

Advertisements

Responses

  1. I personally think that testing private methods is as crucial as public ones. As for the enabling technology, I use Aspect Oriented Programming to access private methods. In fact, I summarized some of the existing workarounds and explained using AOP in a quick blog post
    http://www.khussein.com/wordpress/?p=38

    Please, share your thoughts!


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

Categories

%d bloggers like this: