Learning Test Driven Development with TDD Katas

 

Introduction

In these days Test Driven Development (TDD) is one of the most growing things in the technical world. Most of us are following Agile methodology where we would like to test our code within code.

In this article we will discuss all about TDD Katas and how we can get hands-on with Test Driven Development (TDD).

Why we need to learn TDD?

It’s a real scenario based questions. Lately, I spoke in an engineering college and I have been asked numerous similar questions. Many read books, blogs and some great articles of great authors but they still in doubt why we should work with Test Driven Development? Some were comparing TDD with their Unit testing all pushed me to answer everything. Here, I am sharing my views, what I had talked with all those guys?

  • First of all do not mix Unit Testing and TDD.
  • TDD is just like you are writing and testing your code at the same time.
  • It is something like testing a code from within a code.
  • TDD makes sure that the written code is tested and refactored.

Now, question arise, why we even need to perform or learn TDD? For this just think a scenario a developer did complete unit testing and Quality Assurance guys did their job and marked the deliverables ready for production. What happened if other developer’s code/changes break first developer’s code? Now, here we can think about TDD. As it is self-explanatory that Test Driven Development, means what we are writing, we are testing. In this way, if someone broke your code then your test(s) will get failed and you can check the broken area. This is just a one aspect, TDD is huge one.

So, answer is simple if you want to make your code good follow TDD.

What is TDD Kata?

Kata is a Japanese word and means as ‘form’ and detailed choreographed pattern of body moments.

In martial arts, what they do, they do practice and repeat the steps to hone the skills and their patterns. Similarly, in software the idea originally invented by Dave Thomas. The motive of this idea is same do practice, repeat tasks and make your skills perfect.

Where and when to start?

You can start whenever you want, there is no such extra skills require just you should capable to write code.

Learning phenomena

Here are few learning steps, I am going to share to make your learning for TDD robust and quicker:

Do Katas daily

I would recommend do Katas everyday on daily basis, if you are just going to start learning Katas. This time is beyond your regular programming hours/time.

Choose a calm time to do your katas. I generally do this in the start of my day, I do a 30 minutes kata on every of my morning. Please avoid to do katas on your workplace unless you think that you are ready to do katas in your projects.

Make it in your practice

Although, I don’t do katas everyday but I do Katas all time. In these days, I do Katas to learn new technologies. I learnt good technologies by doing katas in my daily life.

What are available Katas to start?

There are a lot of Katas available to start:

String Calculator Kata (via Roy Osherove)

  • Create a simple String calculator with a method int Add(string numbers). The method can take 0, 1 or 2 numbers, and will return their sum (for an empty string it will return 0). For example "" or "1" or "1,2"
    • Start with the simplest test case of an empty string and move to 1 and two numbers
    • Remember to solve things as simple as possible so that you force yourself to write tests you did not think about
    • Remember to refactor after each passing test
  • Allow the Add method to handle an unknown amount of numbers
  • Allow the Add method to handle new lines between numbers (instead of commas).
    • the following input is ok: "1\n2,3" (will equal 6)
    • the following input is NOT ok: "1,\n" (not need to prove it - just clarifying)
  • Support different delimiters. To change a delimiter, the beginning of the string will contain a separate line that looks like this: [delimiter]\n[numbers...], for example ;\n1;2 should return three where the default delimiter is ; .
    • The first line is optional. all existing scenarios should still be supported
  • Calling Add with a negative number will throw an exception "negatives not allowed" - and the negative that was passed.
    • if there are multiple negatives, show all of them in the exception message

The Bowling Game Kata (via Uncle Bob)

  • Create a new project or start in the existing project by adding Game.cs and TestGame.cs
  • Create two public methods
  • Create Test Methods for the above Methods
  • This is called a 'RED' Test as it is going to fail.
  • Rectified both test and class methods
  • Write new test
  • This is called a 'Green' Test as it is going to pass.
  • Rectified TestMethods to meet total 20 frames hit.
  • Rectified test to accept multiple frame and pins
  • Test 3 is a 'Red' test
  • Test 4 and 5 are 'Green'
  • All test passed
  • Still there is scope of refactoring

The FizzBuzz Kata

 Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz” instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

There are many more available here: Practicising Katas

Lets start here with me to do Katas

What are you waiting for, lets start Katas just from here.  As we have already discussed about Test Driven Development.

TDD is having three stages called Red Green Refactor (RGR).

  1. Red – First write test that fails
  2. Green – Modify/alter code so, test pass.
  3. Refactor- Re-write the code better

To understand let’s take an example of FizzBuzz Kata – a very simple Kata. To start writing this Kata, we need to create a Unit Test project, here I am using NUnit Test Framework, you can use as per your choice:

  • Launch Visual studio
  • Create New Project (C# library project) by pressing ctrl + shift + N
  • Named it as per your choice, I named it ‘TDD-Katas-project’
  • Add two classes named as ‘FizzBuzz.cs’ and ‘TestFizzBuzz’
  • Add NUnit support to your project: add nugget package of NUnit using either Console Manager or Nuget UI Dialog.

We are ready to get start. Get back to description of our kata, first says ‘Write a program that prints the numbers from 1 to 100’.

At very first instance we can write simple snippet which just prints numbers between 1 – 100, so, add following snippet to FizzBuzz.cs:

public string  PrintNumber()  
 {
 var number = string.Empty;
 for (var i = 1; i < 100; i++)
 number += " " + i;
 return number.Trim();
 }

Lets write a test for this as per our Kata we need to write a Fizz if a number is divisible by 3. Add following test in Test FizzBuzz.cs file:

[Test]
 public void  CanReturnFizzIfNumberDivisibleByThree()
 {
 var actualResult = FizzBuzz.PrintNumber();
 Assert.True(actualResult.Contains("Fizz"));
 }

Run above test from within Visual Studio, I am using Resharper, so, I get the results in Unit Test window as:

http://www.c-sharpcorner.com/UploadFile/g_arora/learning-test-driven-development-with-tdd-katas/Images/run%20app.jpg

Here, our test get failed and it is a Red stage.

Now, we know we have a failed test and we know the reason why our test get failed. Correct the code so, our test get passed.

Modify our above snippet and it looks like:

public static  string PrintNumber()
 {
 var number = string.Empty;
 for (var i = 1; i < 100; i++)
 {
 number += i%3 == 0 ? " " + "Fizz" : " "  + i;
 }
 return number.Trim();
 }

Now, again run the same test to see whether it pass or fail.

http://www.c-sharpcorner.com/UploadFile/g_arora/learning-test-driven-development-with-tdd-katas/Images/RUN%20APP%20AGAIN.jpg

Good to see that we wrote code so, our test pass.

Here our test pass, so, it is a Green stage.

Now, revisit the code snippet to see if there is any possibility to refactor the code, lets see: In above we are checking if number is divisible by 3 then it should be ‘Fizz’, yes, here we can refactor our code:

Create one method which lets us know whether a number is a Fizz or not:

private static  bool IsFizz(int i) 
 {
 return i % 3 == 0;
 }

And make a call to this method in our responsible method as:

public static string PrintNumber()

{
var number = string.Empty;
for (var i = 1; i < 100; i++)
number += IsFizz(i) ? " " + "Fizz" : " "  + i;
return number.Trim();
}

Here we refactored our code so, we’re at Stage Refactoring. Now, repeat all these stages until you complete all the points of FizzBuzz Kata. Remaining points are:

  • For the multiples of five print "Buzz".
  • For numbers which are multiples of both three and five print "FizzBuzz"
  • Else print number itself

A complete source code is attached, you can download and enjoy the Kata Game J

Closing notes

In this article we discuss the importance of Test Driven Development and we did get into how we can learn TDD with the use of Katas. We also, discuss about what is a TDD Kata with one short example.

Other languages