How to apply TDD approach for a Go application

TDD stands for Test Driven Development is a software development process which focuses on ensuring the updated code does not break existing features by always writing the tests first and then writing code to satisfy the written tests. In this article, let’s see how you can apply TDD for a Go application.

Donald Le
3 min readFeb 21

--

In software projects, we are often bound by the delivery deadline. Since everyone in the team needs to strive hard to meet the expected deadline, developers tend to avoid unit testing. As a result, the implementation code is not designed to have unit test in mind, which makes it really hard for developers to write unit test later when they have time. Without design for testing, like dependency injection, we will have to refactor a lot of code to write unit test. And because of lacking unit test, we can’t be sure whether our code changes break the existing functionalities of the app or not. This is a real block for developers to write the test and in the end, we might end up not having any test at all.

This is why we need to approach writing unit test with Test Driven Development. In TDD, you write the test first, then write the code just to make the test pass, then refactor the code to meet the expected software design. By having the test first, we are certain that we follow the expected criteria of the feature. In addition, we can confidently update the code. If anything breaks, we will be notified instantly by running the test.

For example, let’s say we want to implement a simple calculator app. We will start with the adding function first. Since we want to apply TDD, we will write the failed test first.

package calculator_test

import (
"calculator"
"testing"
)

func TestAdd(t *testing.T) {
t.Parallel()
var want float64 = 4
got := calculator.Add(2,2)
if want != got {
t.Errorf("want %f, got %f", want, got)

}

}

In this test, we suppose we have a function named Add that has been implemented. We expect that the result of using Add function with input is 2+2 will equal to 4.

--

--

Donald Le

A passionate automation engineer who strongly believes in “A man can do anything he wants if he puts in the work”.