Practical TDD in Go: Why a Green Test Needs to Fail FirstArticle · digest for October 18
First-person still life of a programmer's desk: hands over a keyboard and a terminal running parallel TDD tests in Go.
Article3 sections≈ 5 min

Practical TDD in Go: Why a Green Test Needs to Fail First

You have probably heard the classic joke about the developer with 100% test coverage whose service panics the moment it hits production. I explored a similar illusion earlier when looking at why a green linter doesn't guarantee reliable tests. Unit testing has the exact same trap: a green bar in your terminal doesn't prove your test can actually catch bugs.

Well-known engineer and author of The Power of Go: Tests John Arundel put this paradox bluntly: a test that has never failed in front of your eyes isn't worth trusting.

Let's walk through a classic TDD (Test-Driven Development) cycle using a seemingly trivial task—an IsSorted function that checks whether a slice of integers is sorted in ascending order.

Programming Backwards: From Red to Green

What does a developer do without TDD? They immediately write a for loop, compare elements, and then slap on a check for []int{1, 2, 3}. The test passes. Everyone is happy.

Wait—what if a typo crept into the code, or the function literally consists of a single line return true? That test would still stay green! You have bought yourself a false sense of security.

In TDD, we flip the process on its head:

  1. Red phase. We declare the call we want—sorted.IsSorted(input)—and write a minimal stub so it compiles, returning a deliberately wrong answer: return false. We run go test and verify with our own eyes that the test fails with a clear error message. The test is alive!
  2. Symmetric check. We add a case for unsorted data: []int{1, 3, 2} -> false. Now no hardcoded constant (true or false) can fool our test runner.
  3. Shameless Green phase. We write the simplest working code possible, even if it looks naive.

How Edge Cases Evolve in the Algorithm

Moving from naive code to production-ready logic is where classic edge-case traps surface:

  • Negative numbers: if you initialize the previous-value variable to zero (prev := 0), the slice []int{-1, 2, 3} will falsely register as unsorted (-1 < 0). You must initialize it strictly with the first element of the slice!
  • Empty slices: indexing input[0] on an empty slice []int{} immediately triggers a fatal panic: runtime error: index out of range. You need a boundary guard: len(input) < 2.
  • Duplicates: elements like []int{1, 2, 2} must count as sorted, so the failure condition is strictly v < prev.

Table-Driven Tests and Parallelism in Go 1.22+

The ideal pattern for these checks in Go is table-driven tests paired with t.Run subtests and t.Parallel():

package sorted_test

import (
    "testing"
    "github.com/example/sorted"
)

func TestIsSorted_TableDriven(t *testing.T) {
    t.Parallel()

    tests := []struct {
        name  string
        input []int
        want  bool
    }{
        {"sorted slice", []int{1, 2, 3}, true},
        {"duplicate elements", []int{1, 2, 2}, true},
        {"negative numbers", []int{-1, 2, 3}, true},
        {"empty slice", []int{}, true},
        {"single element", []int{42}, true},
        {"out of order at end", []int{1, 3, 2}, false},
        {"reverse order", []int{3, 2, 1}, false},
    }

    for _, tc := range tests {
        // In Go 1.22+, shadowing tc := tc is no longer needed:
        // loop variables are now scoped per iteration
        t.Run(tc.name, func(t *testing.T) {
            t.Parallel()
            got := sorted.IsSorted(tc.input)
            if got != tc.want {
                t.Errorf("IsSorted(%v) = %v, want %v", tc.input, got, tc.want)
            }
        })
    }
}

Refactoring Phase: Switching to slices.IsSorted

Once every edge case is locked down by tests, comes every engineer's favorite stage—refactoring. Why maintain a hand-rolled loop when Go 1.21+ introduced the generic slices package in the standard library?

We simply throw away our custom code and replace it with the standard library call:

package sorted

import "slices"

// IsSorted checks whether elements of any ordered type are sorted
func IsSorted(input []int) bool {
    return slices.IsSorted(input)
}

Run go test -v -race ./...—all seven parallel subtests light up green. We refactored the implementation in seconds while remaining 100% certain that not a single edge case broke. That is the real superpower of TDD.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 3