Click here to Skip to main content
15,860,972 members
Articles / Web Development / HTML

Learning Test Driven Development with TDD Katas

Rate me:
Please Sign up or sign in to vote.
4.69/5 (9 votes)
14 Mar 2015CPOL8 min read 77.8K   271   18   16
In this article, we will discuss all about TDD Katas and how we can get hands-on with Test Driven Development (TDD).

Contents

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).

Katas

Why We Need to Learn TDD?

It’s a real scenario based questions. Lately, I spoke in an engineering college at Noida, India 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, the question arises, why we even need to perform or learn TDD? For this, just think of a scenario where a developer did complete unit testing and the Quality Assurance guys did their job and marked the deliverables ready for production. What happened if the other developer’s code/changes break the first developer’s code? Now, here we can think about TDD. As it is self-explanatory, 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 a huge one.

So, the 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 was originally invented by Dave Thomas. The motive of this idea is the same, do practice, repeat tasks and make your skills perfect.

Where and When to Start?

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

Learning Phenomena

Here are a 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 a 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 every morning. Please avoid doing katas at your work place 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. 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 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 simply 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.
  • 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 tests passed
  • Still there is scope of refactoring

The FizzBuzz Kata

Print 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

Let's Start Here With Me to do Katas

What are you waiting for, let's start Katas just from here as we have already discussed about Test Driven Development.

What is TDD?

As per wiki, TDD is defined as:

"Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: first the developer writes an (initially failing) automated test case that defines a desired improvement or new function, then produces the minimum amount of code to pass that test, and finally refactors the new code to acceptable standards"

TDD

TDD has three stages called Red Green 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 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 say ‘Write a program that prints the numbers from 1 to 100’.

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

C#
public string PrintNumber()
        {
            var number = string.Empty;
            for (var i = 1; i < 100; i++)
                number += " " + i;

            return number.Trim();
        }

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

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

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

Failed Test

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 gets failed. Correct the code so our test gets passed.

Modify our above snippet and it looks like:

C#
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 will pass or fail.

Passed Test

Good to see that we wrote code so our test passes.

Here is 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, let's see: In the 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:

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

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

C#
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. :)

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.

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.

History

  • 13th March, 2015: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer
India India
Learning never ends.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Mahsa Hassankashi18-Mar-15 11:55
Mahsa Hassankashi18-Mar-15 11:55 
GeneralRe: My vote of 5 Pin
Gaurav Aroraa19-Mar-15 2:11
professionalGaurav Aroraa19-Mar-15 2:11 
GeneralMy vote of 5 Pin
Usha mor18-Mar-15 3:08
Usha mor18-Mar-15 3:08 
GeneralRe: My vote of 5 Pin
Gaurav Aroraa19-Mar-15 2:12
professionalGaurav Aroraa19-Mar-15 2:12 
Questioneasy and simple Pin
Member 1153105216-Mar-15 20:37
Member 1153105216-Mar-15 20:37 
AnswerRe: easy and simple Pin
Gaurav Aroraa16-Mar-15 20:56
professionalGaurav Aroraa16-Mar-15 20:56 
QuestionGood explanation Pin
Shubh Computing16-Mar-15 3:23
Shubh Computing16-Mar-15 3:23 
AnswerRe: Good explanation Pin
Gaurav Aroraa16-Mar-15 5:06
professionalGaurav Aroraa16-Mar-15 5:06 
GeneralMy vote of 5 Pin
Shuby Arora15-Mar-15 22:34
Shuby Arora15-Mar-15 22:34 
GeneralRe: My vote of 5 Pin
Gaurav Aroraa15-Mar-15 22:42
professionalGaurav Aroraa15-Mar-15 22:42 
GeneralRe: My vote of 5 Pin
Shuby Arora15-Mar-15 23:18
Shuby Arora15-Mar-15 23:18 
GeneralRe: My vote of 5 Pin
Gaurav Aroraa16-Mar-15 5:07
professionalGaurav Aroraa16-Mar-15 5:07 
GeneralMy vote of 5 Pin
Camilo Reyes15-Mar-15 15:44
professionalCamilo Reyes15-Mar-15 15:44 
AnswerRe: My vote of 5 Pin
Gaurav Aroraa15-Mar-15 20:07
professionalGaurav Aroraa15-Mar-15 20:07 
GeneralRe: My vote of 5 Pin
Shuby Arora15-Mar-15 23:18
Shuby Arora15-Mar-15 23:18 
GeneralRe: My vote of 5 Pin
Gaurav Aroraa16-Mar-15 5:07
professionalGaurav Aroraa16-Mar-15 5:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.