Testing in GoAdvanced
1Question 1 of 1
goHow does Testing in Go work with the testing package and Table-Driven Tests?
Explanation & Concept
Go includes a built-in testing framework (`go test`). Test files are named with the `_test.go` suffix.
**Table-Driven Tests** are the Go idiom: defining test cases as an array/slice of structs containing inputs and expected outputs, iterated using `t.Run()`.
Code Example
go
package mathutil_test
import "testing"
func Add(a, b int) int { return a + b }
func TestAdd(t *testing.T) {
cases := []struct {
name string
a, b int
expected int
}{
{"positive numbers", 2, 3, 5},
{"negative numbers", -2, -3, -5},
{"zero value", 5, 0, 5},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := Add(tc.a, tc.b)
if got != tc.expected {
t.Errorf("Add(%d, %d) = %d; expected %d", tc.a, tc.b, got, tc.expected)
}
})
}
}How It Works & Key Takeaways
Table-driven tests make adding new edge cases as simple as adding a single line to the test slice.
Mock Test · 1 Questions · Optional
Ready for Garbage Collection?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced2 questions