Archive for the ‘BDD’ Category

Don’t name your test for the class under test

Tuesday, March 11th, 2008

Whenever I play in a new language one of the first things I do is to install the appropriate xUnit framework to get feel for the language.  For my Java code I have been using JUnit for many years.  My use of JUnit hasn’t really changed over the years, but some things have been bugging me for a while.

One of the things that has bugged me is naming the test class for the class under test.  That is, if the class under test is Banana your test class would be called BananaTest.  There are obvious advantages to this pattern:

  1. You know where to look for the test code for a class
  2. You can find all the test classes very easily - using filename pattern matching.

However, there are several disadvantages.  One is that it ties you to having a single test class for each class which can cause problem.  I have often found myself writing or maintaining large test classes that combine testing different aspects of the class’ behaviour.  Some of these classes would exceed Checkstyle’s line length limit for a method.  One solution to this is to blindly split the class into two classes.  What then to call the new class?  Banana2Test - not very descriptive or helpful.  Maybe we should name the test for the aspect of things we are testing, e.g. BananaSlippynessTest or BananaFlavourTest.  But now the test isn’t following the original naming convention.  This isn’t a big problem, but is there maybe something we can learn from this.

Apparently there is.  Yesterday I attended an Agile Vancouver workshop - “BDD and TDD code off”.  Our group chose to use TDD which is still fairly new to me.  I was lucky though that Peter, who was in our group, was an experienced TDD’er.  It was an interesting experience and the code we produced was a little different to the code I would normally produce.  I don’t yet know if the code was better or worse, for now it was just ‘different’.

That workshop drove me to learn a little more about BDD, so I watched the Google Talk of David Astels introducing BDD and he mentioned how BDD tests are typically structured - around the different expected behaviours.  One example he gave was testing a List class.  You would likely have a test class called EmptyList which would contain the specifications for an empty list.  For example: Ensure list has size = zero, Ensure list iterator has no items.  This test class would contain the specifications for just empty lists.  I assume you would then add a test class for a non empty list, and perhaps another to ensure the ordered-ness of list, and possibly several more.

I’m not sure if I’ll be adopting this in my current project at work just yet.  Doing something different without hard and fast rules can confuse people and can put people off testing, which I really don’t want to happen.  However, in my pet projects and fiddlings I think I’ll be experimenting a little more.