Lesson 11 of 60 · Go
Testing in Go: The `testing` Package
Duration: 20 minutes
Testing in Go: The testing Package
Testing is built into Go. This lesson explains how to write unit tests, run them, and use table-driven patterns.
Unit testing
Create a file ending in _test.go and use the testing package.
package main
import "testing"
func TestAdd(t *testing.T) {
got := add(2, 3)
want := 5
if got != want {
t.Fatalf("add(2,3) = %d; want %d", got, want)
}
}
Run tests with:
go test ./... -v
Table-driven tests
Use a slice of cases to test many inputs with the same logic.
func TestIsEven(t *testing.T) {
cases := []struct{ in int; want bool }{{2,true},{3,false},{0,true}}
for _, c := range cases {
if got := isEven(c.in); got != c.want {
t.Errorf("isEven(%d) = %v; want %v", c.in, got, c.want)
}
}
}
Benchmarks
Benchmark code measures performance and runs repeatedly.
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
add(i, i)
}
}