Skip to content

Go Test Table Driven

DodaTech 2 min read

In this tutorial, you'll learn about Go Test: Table. We cover key concepts, practical examples, and best practices.

Table-driven tests -- Write concise, comprehensive test coverage using table-driven test patterns.

The Problem

Instead of repeating test code for each case, use a table of inputs and expected outputs with a single test loop. Use t.Run() for subtests with independent reporting.

Wrong

func TestAdd(t *testing.T) {
    if add(1, 2) != 3 { t.Error("1+2 != 3") }
    if add(0, 0) != 0 { t.Error("0+0 != 0") }
    if add(-1, 1) != 0 { t.Error("-1+1 != 0") }
}

Output:

// Repetitive, hard to maintain, first failure stops
func TestAdd(t *testing.T) {
    tests := []struct {
        name string
        a, b int
        want int
    }{
        {"positive", 1, 2, 3},
        {"zeros", 0, 0, 0},
        {"negative", -1, 1, 0},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := add(tt.a, tt.b); got != tt.want {
                t.Errorf("add(%d,%d) = %d, want %d", tt.a, tt.b, got, tt.want)
            }
        })
    }
}

Output:

// All cases run independently. Clear naming.

Prevention

  • Use struct for test cases with name, input, expected
  • Use t.Run() for subtests
  • Each subtest runs independently
  • Failure in one does not stop others
  • Use t.Parallel() for concurrent subtests

Common Mistakes with test table driven

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. Forgetting deriving (Show, Eq) on custom data types needed for debugging

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**How to handle test setup/teardown for each case?**

Use t.Cleanup() or run setup inside t.Run().

Can I use map for test cases?

Yes. Map keys serve as test names.

What about random test data?

Use fuzz testing for random inputs.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro