Lets create a simple TDD sample

Vahid Farahmandian
3 min readJul 4, 2021

--

We all might have an idea about what is TDD. In this article, I do not want to talk philosophically about TDD, By the way, I just want to show you a small example.

Source Code: Simple_TDD_Sample on GitHub

In order to write a unit test, simply we need to consider the following steps:

1. Write a test that fails

2. Write a code that makes your unit test to pass

3. Refactor your code and do not let your unit test to become fail

Ok lets start…

Suppose that you have given a task to write a function which accepts two integer value and returns the sum of them.

First I am going to write a test that fails. So it will not be that hard.

Now I have my unit test, but clearly it will be failed. Because I am not even able to compile this code. Why? Because I have not any class with name “MyMath” and specifically I do not have any method inside that class with name “Sum”. So what should I do? I should write a simplest possible code which makes my test to pass. Lets write it then…

Great! Now I have a code which compiles successfully and also passes my unit test. Why I have return “0” from my method? Because I just want to write a simplest possible code which makes my code to pass!

But this is not the requirement! No problem, I can now refactor my code until it fulfills the requirement, provided that it passes my unit test. Lest do it so…

Ahha, now I have a code which fulfills the requirement plus it’s unit test is passed too…

Now new requirements might arise. For instance I need to change the method in a way that it only return the sum of two POSITIVE integers and for negative inputs it should return 0.

What should I do then?

Simply refactor the method in a way that it still passes the unit test. So it is clear that from now on, any modification to my method should start from unit test(write a new test or change the current test)

It seems that it was not that hard to start writing unit tests, so why not to write unit test for our methods? :-)

Source Code: Simple_TDD_Sample on GitHub

--

--