The diary of a .NET Developer, working on an unlaunched startup project. Also, I live and work in Southern Oregon.

Sunday, January 18, 2009

Testing private methods

I am writing a crossword word search puzzle solver for the purpose of practicing Test Driven Development.  Yep, I am only writing code after first writing a test. 

I started off with a very powerful method named SolveForWord:

   public class PuzzleSolver
{
public PuzzleSolution SolveForWord(string word)
}


Almost instantly, I had the urge to start writing private methods to help parse the puzzle into a private data-structure.   But since I’m doing TDD, I had to think about how to continue.  Since I can’t test private methods, how do I write that code? 



To be honest what I did next was find out how other people do in this situation.  After a bit of googling, I decided to try testing my private methods using reflection.  Then it hit me.  My attempt to test private methods was “test friction” right?  The PuzzleSolver class shouldn’t be doing any parsing!  By experiencing this “test friction” I changed my design. 



   public class PuzzleParser
{
public PuzzleParser(string text)
{
}
}


PuzzleSolver will use PuzzleParser to perform parsing and not actually perform parsing itself. Single Responsibility in action!



Note: I didn’t know how much code to include in my post, so I purposely left out most of it.

2 comments:

  1. Ben, I listened to the same episode of Hanselminutes with great interest. It challenged some of my beliefs and notions about TDD.

    I am thinking now in the same vein as this post of yours. Basically, a method or class should have one reason to change. A related phrase: it does one thing, and does it well.

    Here's a decent start for more ideas on test friction and zero friction TDD:
    http://blogs.msdn.com/ploeh/archive/2008/11/13/zero-friction-tdd.aspx

    ReplyDelete
  2. Thanks for the link. I'm reading through it now and bookmarking like crazy!

    ReplyDelete