Learning Test Driven Development With TDD Katas

Table of Contents

  • Introduction
  • Why to learn TDD
  • What TDD Kata is
  • Where and when to start
  • Learning phenomena
  • Do Katas daily
  • Make it in your practice
  • Available Katas to start
  • String Calculator Kata (via Roy Osherove)
  • The Bowling Game Kata (via Uncle Bob)
  • The FizzBuzz Kata
  • Let's start here with me to do Katas
  • Closing notes

    Introduction

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

    This article explains TDD Katas and how to get hands-on with Test Driven Development (TDD).


    Why to learn TDD

    They are 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 are still in doubt about why to work with Test Driven Development. Some were comparing TDD with their unit testing and they all presurred me to answer everything. Here, I am sharing my views, what I have said to 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, the question is, why do we even need to do or learn TDD? For this just think of a scenario in which a developer has completed the unit testing and the Quality Assurance guys have done their job and marked the deliverables ready for production. What happens if other developer's code/changes break first developer's code? Now, here we can think about TDD. Since it is self-explanatory that Test Driven Development, in other words what we are writing, we are testing. In this way, if someone broke your code then your test(s) will fail and you can check the broken area. This is just one aspect, TDD is a huge one.

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

      What TDD Kata is

      Kata is a Japanese word meaning "form" and a detailed and choreographed pattern of body movements.

      In Martial Arts, what they do is practice and repeat the procedure to hone the skills and their patterns. Similarly, in software the idea was originally invented by Dave Thomas. The purose of this idea is the same; that is, practice and repeat the tasks and make your skills perfect.

      Where and when to start

      You can start whenever you want, these is no such extra skills required, you should just be capable of writing code.

      Learning phenomena

      Here are a few learning procedures I will share to make your learning of TDD robust and quicker.

      Do Katas daily

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

      Choose a calm time to do your Katas. I generally do this in the beginning of my day, I do 30 minute Katas every morning. Please avoid doing Katas in your workplace unless you think that you are ready to do Katas in your projects.

      Make it your practice

      Although I don't do Katas everyday, I do Katas all the time. In these days, I do Katas to learn new technologies. I learned good technologies by doing Katas in my daily life.

      Available Katas to start

      There are many 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".

           o Start with the simplest test case of an empty string and move to 1 and two numbers
           o Remember to solve things as simply as possible so that you force yourself to write tests you did not think of
           o 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).

           o the following input is okay: "1\n2,3" (will equal 6)
           o the following input is not okay: "1,\n" (no need to prove it, just clarifying)

      • Support various 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:

           o The first line is optional. All the 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.

           o 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 preceding Methods.
      • This is called a "RED" Test since it will fail.
      • Rectified both test and class methods.
      • Write new test.
      • This is called a "Green" Test since it will 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 that are multiples of both three and five print "FizzBuzz".

      There are many more available here: Practicising Katas

      Let's start here with me to do Katas

      What are you waiting for? Let's start Katas just from here, since we have already discussed Test Driven Development.



      TDD has the three stages called Red, Green and Refactor (RGR).

      Red: First write test that fails.
      Green: Modify/alter code so, test pass.
      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 the NUnit Test Framework, you can use whatever you choose:

      • Launch Visual Studio.
      • Create a New Project (C# library project) by pressing Ctrl + Shift + N.
      • Name it as you choose, I named it "TDD-Katas-project".
      • Add two classes named "FizzBuzz.cs" and "TestFizzBuzz".
      • Add NUnit support to your project: add a Nugget package of NUnit using either Console Manager or Nuget UI Dialog.

        We are ready to start. Returning to the description of our Katas, the first says "Write a program that prints the numbers from 1 to 100".

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

        1. public string PrintNumber()  
        2. {  
        3.    var number = string.Empty;  
        4.    for (var i = 1; i < 100; i++)  
        5.    number += " " + i;  
        6.    return number.Trim();  
        7. }  
        Let's write a test for this. As per our Kata we need to write a Fizz that tests if a number is divisible by 3. Add the following test in the Test FizzBuzz.cs file:

        1. [Test]  
        2. public void CanReturnFizzIfNumberDivisibleByThree()  
        3. {  
        4.    var actualResult = FizzBuzz.PrintNumber();  
        5.    Assert.True(actualResult.Contains("Fizz"));  
        6. }  

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



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

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

        Modify the preceding snippet and it looks like:

        1. public static string PrintNumber()  
        2. {  
        3.    var number = string.Empty;  
        4.    for (var i = 1; i < 100; i++)  
        5.    {  
        6.       number += i%3 == 0 ? " " + "Fizz" : " " + i;  
        7.    }  
        8.    return number.Trim();  
        9. }  
        Now, again run the same test to see whether it passed or failed.



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

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

        Now, revisit the code snippet to see if there is any possibility to refactor the code, let's see. In the preceding we are checking if the number is divisible by 3. If it is then it should be "Fizz", yes, here we can refactor our code.

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

        1. private static bool IsFizz(int i)  
        2. {  
        3.    return i % 3 == 0;  
        4. }  
        And make a call to this method in our responsible method as:
        1. public static string PrintNumber()  
        2. {  
        3.    var number = string.Empty;  
        4.    for (var i = 1; i < 100; i++)  
        5.       number += IsFizz(i) ? " " + "Fizz" : " " + i;  
        6.    return number.Trim();  
        7. }  
        Here we refactored our code, so we're at Stage Refactoring. Now, repeat all these stages until you have completed all the points of FizzBuzz Kata. The remaining points are:
        • For the multiples of five print "Buzz".
        • For numbers that are multiples of both three and five print "FizzBuzz".
        • Else print the number itself.

          Complete source code is attached, you can download and enjoy the Kata Game.

          Closing notes

          This article explained the importance of Test Driven Development and we did get into how to learn TDD with the use of Katas. We also explained what a TDD Kata is with one short example.

          I hope you enjoyed this article. I tried to make this as simple as I can. If you like this article, please rate it and share it to share the knowledge.


            Similar Articles