Learning Test Driven Development with TDD Katas - CodeProject

:

Contents

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

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.

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.

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

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

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.

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.

There are lot of Katas available to start:

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

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

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

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:

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:

[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:

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:

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

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