Back to Concepts Roadmap
🔥 Level 12 — Architecture & Practices
Architecture

Table-Driven Testing & Mocks

Writing idiomatic Go tests with slices of test cases and t.Run subtests.

Real-World Analogy (Mental Model)

A car crash-test facility: running a standardized checklist of 20 different speed and angle tests through the exact same testing harness.

Key Concepts & Rules To Remember

  • Table-driven tests define a slice of test cases and iterate with `t.Run`.
  • `go test -v -cover` verifies test coverage.
Step-by-Step Code

1. Understanding Table-Driven Testing & Mocks

Writing idiomatic Go tests with slices of test cases and t.Run subtests. In Go, table-driven testing & mocks is designed around clarity and high runtime efficiency.

example.goGo 1.24+
func TestAdd(t *testing.T) {
    tests := []struct{ a, b, want int }{
        {1, 2, 3},
        {-1, 1, 0},
    }
    for _, tt := range tests {
        if got := Add(tt.a, tt.b); got != tt.want {
            t.Errorf("got %d, want %d", got, tt.want)
        }
    }
}

Common Beginner Pitfalls & Mistakes

Mistake: Misusing table-driven testing & mocks without understanding its memory or concurrency semantics.
✅ Correct Way: Always follow standard Go idioms and verify with tests.
Self Assessment

Knowledge Check

Verify your understanding with these interactive practice questions.

Quizzes

Quick checks for understanding

Multiple-choice with inline explanations—expand to see why.

What is the primary concept behind Table-Driven Testing & Mocks?

Finished this lesson?

Mark it as complete to track your overall Go mastery.