Mastering Go’s test Command: Parameters, Benchmarks, and Profiling Techniques
This article explains how to use Go's test command with various flags such as -c, -run, -timeout, and -coverprofile, demonstrates writing test cases, TestMain setup, benchmarking, profiling with pprof, generating flame graphs, and interpreting coverage reports to improve Go application reliability and performance.
The go test command offers many flags that allow you to compile test binaries, pass custom parameters, run specific tests, set timeouts, generate coverage reports, and perform benchmarks.
When a package requires command‑line arguments (e.g., a log_dir flag for the glog library), you normally build the binary with go build main.go and run it with ./main -log_dir="/data". To pass the same argument to go test, use the -c flag to compile a test binary first: go test -c param_test_dir Running the compiled test binary executes all Test functions. To run only a specific test, use the -run flag with a matching pattern, e.g.: go test -v -run Logger2 ./util/ Note that -run does not work together with -c in the same command.
option
The default go test timeout is 10 minutes; exceeding it causes a panic. Set -timeout 0 to disable the limit:
nohup go test -v -timeout 0 -run TestGetRange . > log.txtTesting with map
You can use closures and the Run method to test functions that operate on maps, providing expected values for each sub‑test.
func TestSum(t *testing.T) {
t.Run("A", testSumFunc([]int{1,2,3}, 7))
t.Run("B", testSumFunc([]int{2,3,4}, 8))
}
func Sum(numbers []int) int {
total := 0
for _, v := range numbers {
total += v
}
return total
}
func testSumFunc(numbers []int, expected int) func(t *testing.T) {
return func(t *testing.T) {
actual := Sum(numbers)
if actual != expected {
t.Error(fmt.Sprintf("Expected the sum of %v to be %d but got %d!", numbers, expected, actual))
}
}
}Main
Define a TestMain function to perform setup and teardown around all tests:
func TestMain(m *testing.M) {
fmt.Println("start prepare")
flag.Parse()
exitCode := m.Run()
fmt.Println("prepare to clean")
os.Exit(exitCode)
}pprof Performance Profiling
Import net/http/pprof to expose profiling endpoints at /debug/pprof/, which provide CPU, memory, block, goroutine, heap, mutex, and thread‑create profiles. import _ "net/http/pprof" Typical endpoints:
/debug/pprof/profile /debug/pprof/block /debug/pprof/goroutine /debug/pprof/heap /debug/pprof/mutex /debug/pprof/threadcreateFetch a CPU profile from the terminal:
pprof -seconds=10 http://192.168.77.77:3900/debug/pprof/profileVisualize the profile with:
pprof -http=:1313 cpu.prof
go tool pprof cpu.prof
$ web | topBenchmark Testing
A basic benchmark repeats a loop b.N times:
func BenchmarkBadgeRelationMapper_GetCountByUid(b *testing.B) {
count := 0
for i := 0; i < b.N; i++ {
count++
}
fmt.Println("total:", count)
}Run benchmarks with go test -bench=.. Use -benchmem to report memory allocations and -benchtime to adjust the run duration.
go test -bench=. -benchtime=20s
go test -bench=. -benchmemParallel benchmarks use b.RunParallel and the PB helper:
func BenchmarkParallel(b *testing.B) {
count := 0
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
count++
}
})
fmt.Println("total:", count)
}Regular Expression for Benchmark Selection
Use -run or -bench with a regex to select specific tests or benchmarks:
go test -bench=. -run=^$ // run no tests
go test -run=Logger2Coverage
Generate a coverage profile with -coverprofile and view it as HTML:
go test -v -coverprofile=c.out
go tool cover -html=c.out -o=coverage.htmlFlame Graphs
Tools such as go-torch and Brendan Gregg’s FlameGraph scripts help visualize CPU profiles as flame graphs.
git clone https://github.com/brendangregg/FlameGraph.git
cp flamegraph.pl /usr/local/bin
go get -v github.com/uber/go-torch
go-torch -u http://192.168.77.77:3900/debug/pprof/profile -t 10Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
