Unit testing privates, and other unsavoury topics

Brian Duff gives a good example of a technique to get around visibility problems when unit testing. Believe it or not, this can be a good idea (and this is a strong TDD advocate saying this).

When using unit tests to drive your design, as in TDD, it would be a seriously bad idea to test private methods, or anything else that is overly implementation specific. It makes the tests to fragile, and will cause problems when it comes time to refactor the design. However, as the saying goes: TDD is about design, not about testing. Sometimes you do need implementation-oriented tests.

In this case, the rules for unit testing for TDD just don’t apply; new rules come into play. Sometimes you can’t tweak the API. Other times, you may not even be able to change the source; for example, when it’s a feature, not a bug. 🙂 Other times, it just may not be atheistically pleasing to do so.

Personally, in Brian’s case, I would have extracted an interface for clients to use that matched what I wanted, and then made the necessary test points public, but that’s my style in a given situation, and each to their own.

Unit testing privates does have its place in verifying the implementation; just don’t use it to do TDD.

Advertisements

Author: Robert Watkins

My name is Robert Watkins. I am a software developer and have been for over 18 years now. I currently work for people, but my opinions here are in no way endorsed by them (which is cool; their opinions aren’t endorsed by me either). My main professional interests are in Java development, using Agile methods, with a historical focus on building web based applications. I’m also a Mac-fan and love my iPhone, which I’m currently learning how to code for. I live and work in Brisbane, Australia, but I grew up in the Northern Territory, and still find Brisbane too cold (after 16 years here). I’m married, with two children and one cat. My politics are socialist in tendency, my religious affiliation is atheist (aka “none of the above”), my attitude is condescending and my moral standing is lying down.

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