Go Common Test
January 22, 2025 · 2 min read · Page View:
If you have any questions, feel free to comment below.
The test methods in Go mainly include three types: unit test, benchmark test, and example test.
First of all:
- You should import the
testing
package first. - In the package directory, all source code files with the suffix
*_test.go
are part of the go test test, and will not be compiled into the final executable file by go build.
Unit Test #
The basic format/signature is:
func TestXxx(t *testing.T) {
// ...
}
Put the _test.go and .go in the same dir, and run go test -v
to execute the test detailed, the go test -cover
to check the coverage of the test.
Benchmark test #
The benchmark test will not be excuted by default, you need to use go test -bench=Xxx
to execute the benchmark test.
The basic format/signature is:
func BenchmarkXxx(b *testing.B) {
for i := 0; i < b.N; i++ {
// ...
}
}
The b.N
is the number of times the test is run, and the b.N
is automatically adjusted by the go test tool.
BenchmarkSplit-8 10000000 215 ns/op
- The
-8
means the test is run on the 8 GOMAXPROCS - The
10000000
means the test is run 10000000 times. - The
215 ns/op
means the test takes 215 nanoseconds average per operation.
go test -bench=Xxx -benchmem
can check the memory allocation and the number of allocations per operation.
BenchmarkSplit-8 10000000 215 ns/op 112 B/op 3 allocs/op
- The
112 B/op
means the test allocates 112 bytes per operation. - The
3 allocs/op
means the test allocates 3 times per operation.
Performance comparison #
// note: the n is the parameter of Fib not the b.N, the b.N is the number of times the test is run. it will be automatically adjusted by the go test tool.
func benchmarkFib(b *testing.B, n int) {
for i := 0; i < b.N; i++ {
Fib(n)
}
}
func BenchmarkFib1(b *testing.B) { benchmarkFib(b, 1) }
func BenchmarkFib2(b *testing.B) { benchmarkFib(b, 2) }
func BenchmarkFib3(b *testing.B) { benchmarkFib(b, 3) }
go test -bench=.
will execute the benchmark test for all functions with the prefix Benchmark
.
func BenchmarkSplit(b *testing.B) {
time.Sleep(5 * time.Second) // some time-consuming operations
b.ResetTimer() // reset the timer(ignore the time above)
for i := 0; i < b.N; i++ {
// some time-consuming operations
}
}
// you can also use this method
func BenchmarkSplit(b *testing.B) {
b.StopTimer()
// some time-consuming operations
b.StartTimer()
for i := 0; i < b.N; i++ {
// some time-consuming operations
}
}
Parallel test #
Signature:
func BenchmarkSplitParallel(b *testing.B) {
// b.SetParallelism(1) // set the number of CPU to use
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
// some time-consuming operations
}
})
}
Example test #
Signature:
func ExampleName() {
// No parameters and no return
}
If you find this blog useful and want to support my blog, need my skill for something, or have a coffee chat with me, feel free to: