Test Driven Development — Test, Test, Test, then Code!

Write minimal code using TDD!

Muhammad Zuhdi
3 min readApr 5, 2021

Have you ever create a ‘big’ application without any tests? How was it? Is it going well? Is it bug-free? Well, creating a ‘big’ application without any tests usually comes to hard to maintain and too complex code because you just write anything that comes to your mind in that time.

To overcome that problem, you can use TDD on your projects. TDD will make things easy for you to code. With TDD, you’ll write minimal code and avoid many code smells that you probably write on creating logic for your application.

Laws of TDD (by Robert . Martin)

  • You may not write production code until you have written a failing unit test.
  • You may not write more of a unit test than is sufficient to fail, and not compiling is failing.
  • You may not write more production code than is sufficient to pass the currently failing test.

Workflow Cycle of TDD

source : https://tinnedfruit.com/list/20181009

TDD has a cycle with 3 states in it, red-green-refactor. In each state, there is some activities that we should do. I’ll try to explain each state based on my practice using TDD in my group project. Let see the explanation below.

Red State

In this state, we should write a little test that doesn’t work. Test that doesn’t work usually called as failing test. A failing test created for determining what a function or class should do in your application.

For example, in my group project, I get a task integrate google oauth with our web server application. Then, I tried to make test for it. I was testing that ‘login function’ at our application will redirect to google oauth endpoint if i access ‘/auth/login’ endpoint in our web server application. Here’s what it’s look like.

Example of unit test

Green State

At this state, we will implement the function so that it will pass the test that we’ve created.

For example, in my group project, I tried to make the implementation of ‘login function’ like this.

Example of implementation code

After implement the function, we will try to run the test and check if it pass the test or not.

As we expected, the implementation pass the test that we created, so that we can jump into next state.

Refactor State

At this state, we should eliminate of code duplication on the implementation. We should get rid of code smells on our code and make the codes more readable for others. Basically, in this state we should follows the convention based on programming language that we use. Then, you can use code formatter to format your code based on the conventions.

To sum up, TDD will drive you to make a minimal and cleaner code. Let’s encourage test-before-code culture in our software development process.

References:

  • Kent Beck. Test-Driven Development By Example.
  • Robert C. Martin. Clean Code.

--

--