Testing & Tooling
Go’s built-in testing story
Section titled “Go’s built-in testing story”Most languages require a third-party testing framework. Go ships everything you need inside the standard library. The testing package provides *testing.T for unit tests, *testing.B for benchmarks, and *testing.F for fuzzing — all driven by a single command: go test.
The go toolchain that ships with every Go installation also includes:
| Tool | Purpose |
|---|---|
go test | Run tests and benchmarks |
go build | Compile packages and binaries |
go run | Compile and run in one step |
go fmt | Format source code (wraps gofmt) |
go vet | Static analysis for common mistakes |
go mod | Module and dependency management |
go doc | Browse package documentation |
What this module covers
Section titled “What this module covers”- go-test — Writing
_test.gofiles,func TestXxx(t *testing.T), and table-driven tests witht.Run. - benchmarks — Measuring performance with
func BenchmarkXxx(b *testing.B)and reading-benchmemoutput. - modules — Managing dependencies with
go mod init,go.mod,go.sum, andgo get. - go-tooling — The everyday commands:
go run,go build,go fmt,go vet, andgo doc.
A function worth testing
Section titled “A function worth testing”The best way to appreciate Go’s testing tools is to start with a pure function — one with no side effects, no I/O, just input and output. The playground below runs Fibonacci from main. In the next lesson you will write a proper _test.go file for exactly this kind of function.
package main
import "fmt"
// Fibonacci returns the nth Fibonacci number (0-indexed).// fib(0)=0, fib(1)=1, fib(2)=1, fib(3)=2, ...func Fibonacci(n int) int { if n <= 1 { return n } return Fibonacci(n-1) + Fibonacci(n-2)}
// IsPrime reports whether n is a prime number.func IsPrime(n int) bool { if n < 2 { return false } for i := 2; i*i <= n; i++ { if n%i == 0 { return false } } return true}
func main() { // Print the first 10 Fibonacci numbers fmt.Println("Fibonacci sequence:") for i := 0; i < 10; i++ { fmt.Printf(" fib(%d) = %d\n", i, Fibonacci(i)) }
// Find primes up to 30 fmt.Println("Primes up to 30:") for n := 2; n <= 30; n++ { if IsPrime(n) { fmt.Printf(" %d\n", n) } }}Loading Go runtime (first run only, ~8 MB)…