Go — Testing
Basic test
func Add(a, b int) int {
return a + b
}
func TestAdd(t *testing.T) {
result := Add(2, 3)
if result != 5 {
t.Errorf("Add(2, 3) = %d; want 5", result)
}
}
Table-driven tests
func TestAdd(t *testing.T) {
tests := []struct {
a, b, want int
}{
{1, 2, 3},
{0, 0, 0},
{-1, 1, 0},
}
for _, tt := range tests {
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)
}
}
}
Benchmarks
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
Add(1, 2)
}
}
Test helpers
func Helper(t *testing.T) {
t.Helper()
// Helper function
}
Mini Practice
Write Go code that:
- Creates a basic test
- Uses table-driven tests
- Writes a benchmark
- Uses test helpers
Up Next
In the next lesson, you'll learn about Packages — organizing Go code.
Related Topics
Frequently Asked Questions about Testing
What is Testing in Go?
Testing is a fundamental concept in Go. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Testing?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Testing.
Why is Testing important in Go?
Testing is essential for Go development. Understanding this concept will help you write better code and solve real-world problems more effectively.