2011-11-11

Code Kata with DDT in JUnit

Quote from Wikipedia

Code Kata is a term coined by Dave Thomas, co-author of the book The Pragmatic Programmer, in a bow to the Japanese concept of kata in the martial arts. A code kata is an exercise in programming which helps a programmer hone their skills through practice and repetition. As of October 2011, Dave Thomas has published 21 different katas.

Today I participated in my first Code Kata initiated by one of our Scrum Masters. My intention was to get to know this concept in more detail and to see if it is a forum to train BDD skills.

Looking back I am sure that a BDD Code Kata needs some preparation but I also got more practice on Data Driven Testing (DDT). We decided to code the kata Roman Numerals.

We started very simple minded with a test, testing that 1 is converted to I, then 2 to II and of course, simple minded as we are we implemented it by concatenating as many I’s as the number has. And of course this implementation first failed for 4.

First we started writing one test method for each new number we wanted to test. The first discussion which came up:

Shouldn’t we just write one test method testing all numbers?

I answer: No – because if you have 10 assertions and the second one fails you will have no hint about the state of the subsequent 8 assertions as JUnit will just stop this very test. Having multiple short test methods has the advantages:

  • Methods are much easier to read.
  • The different failed tests might help to isolate the source of the problem. Let’s say a test for all even number fails than you might have a first hint what to look for.

DDT – what?

Data Driven Testing is to have a set of data to feed a test with. They might come from a file or any other data generator. The allurement having data driven tests is that the code to test might be very short but you can do many boundary tests with nearly no additional costs.

The following is an example how to do DDT with JUnit. It’s the result of the short work we did today and of course far from being perfect or complete:

Conclusion

I will take part in the next Code Kata next week. It was very refreshing to be able to train techniques I use rarely (like DDT) and to discuss several approaches to a problem in a group.

Links

1 comment:

  1. I'm glad you like the idea of katas. By the way, we should have spend more time and finish the exercise. When everyone prepares the kata we will be faster next time and learn even more from each other. Right now we have some room for improvement. I'm also looking forward to next weeks meeting.

    ReplyDelete