Wednesday, May 30, 2018

Test Driven Development (TDD)

What is TDD? How is it different from Unit Tests? How many tests should one write when using a TDD approach? - These and many more questions come to our mind when we think or decide to take a TDD approach.

TDD stands for Test Driven Development and is different from writing Unit Tests Unit Tests refer to what you are testing, -where-as TDD describes when you are testing. To simplify this, with Unit tests we test and verify the smallest possible unit of behavior, wherein with TDD the tests drive the development. We can say that Unit tests are a part of a TDD approach where we write tests before writing the code. It can include Unit tests, functional tests, behavioral tests, acceptance tests, etcetera.

The idea looks simple in theory, and represents a fundamental change to approaching software development.

Red-Green-Refactor cycle:
The key to TDD is the Red-Green-Refactor cycle. Write tests that fail, fix the code and run the tests again - repeat this until they pass. The below diagram explains it well:


RED - Write a failing test which captures the requirements.
GREEN - Implement the functionality by writing just enough code to pass the test.
REFACTOR - Refine/improve the code without adding any new functionality.

And then repeat the whole cycle.

In my opinion, it is always helpful to see the code tested upfront using this painless testing approach. It gives a sense of confidence to us before we start end-to-end tests for the project. Not only this, I believe it gives a fair indication of code coverage, fewer defects and easy maintenance as well.

As important as it is to start with this approach, it is equally important to make modifications, whilst continuing using the approach. Considering a real-world situation, applications change and over time a method may be removed/added/modified. While making any modifications in the code at a later stage in time, we should run all the tests written until now to ensure that we did not break any functionality while adding/modifying code. In my experience, this reduces the testing time by more than half.

It is very important to monitor the code coverage though the development/maintenance cycle of the application. With code coverage, we get to know if any code is not being called by a test. The two scenarios that will be applicable here are: the code is missing a corresponding test, or it is dead code and needs to be removed.

As writing-running-fixing tests consumes time, it is very tempting to put the writing of tests on the back-burner. The most pressing and difficult aspect of this is to keep the discipline and continue the practice. When it comes to shipping robust, high quality products the benefits of this approach are rewarding!

At nsquared we are working using TDD on our latest products. If you want to find out more about how we work, please get in touch.

Tripti Wani

No comments: