Introduction to Test-Driven Development (TDD) in Go

Test-Driven Development (TDD) is a development methodology that involves writing tests before the actual code. In Go, thanks to native support for testing via the testing package, it's particularly simple to adopt this practice.

What is TDD?

TDD follows a three-phase cycle:

  • Red: write a test that fails.
  • Green: write the minimal code to make the test pass.
  • Refactor: improve the code while keeping the tests green.

First example in Go

Let's suppose we want to implement a function that adds two integers. We start by writing the test.

package sum

import "testing"

func TestAdd(t *testing.T) {
    result := Add(2, 3)
    expected := 5

    if result != expected {
        t.Errorf("Add(2, 3) = %d; want %d", result, expected)
    }
}

This test will fail because the Add function hasn't been implemented yet.

Minimal implementation

Now let's write the code to make the test pass.

package sum

func Add(a, b int) int {
    return a + b
}

Now, running the test with go test should pass.

Useful tools

Go provides several tools for testing:

  • go test to run the tests.
  • -v for verbose output.
  • go test -cover to view code coverage.

Conclusion

TDD helps design reliable and maintainable code. In Go, thanks to the simplicity of the language and good test integration, it's easy to adopt this methodology from the start.

Back to top