Test Driven Development – Getting Started

Test Driven Development (TDD) has been around for years, but I have only recently started using it myself. Previously when working on a project I would write the code for the project, then create unit tests after.

With TDD you reverse your thinking. Think less about the code you intend to write and instead about what you expect it to do. Write a test. Write the barest amount of code to allow the test to run but with a fail. Then write the code so the test will pass. Write a test for your next piece of functionality and continue the cycle. Eventually, refactor your code to remove duplication. A good way of thinking of this process is ‘Red – Green – Refactor’.

Why would you want to do this? Because as a developer you want to ensure the quality & functionality of your code as much as possible. This approach gives you a much higher frequency of feedback on whether your code is doing what you actually want it to do.

Lets look at a basic example.

I have a simple calculator that takes two numbers and a calculation (+,-,*,/).

I write my first test, for the Add method. In order for this to work at it’s most basic level I also have to declare the first number, second number and an Add method

Obviously this fails – I haven’t actually set the Add method to return a value. There’s my first “red”. To accomplish the “green” I update my Add method to actually add the two numbers together.

Following the TDD process, I end up with a test for each calculation type, and a method that each test calls to carry out the appropriate functionality.

As you can see, although I have a test for each method, I am repeating my code quite a bit. It’s unwieldy. So I refactor

And change the tests to call the new property for each calculation test

From here I can extend my tests to cover different scenarios – for example:-

Which results in my changing the code to:-

This is an extremely simple example of TDD, but hopefully it helps provide an example of how straight forward the process is.

Happy coding!

Sources
Guidelines for Test-Driven Development
Test-driven development
TDD – Guide to Agile Practices

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s