As a Gopher, in addition to writing business logic code, I also need to write a lot of unit tests, which accounts for a large part of the workload, enough to show its importance.
Project structure
Our project structure should be similar to the following, and there calc.go
will be a calc_test.go
corresponding test case file:
example/
|--calc.go
|--calc_test.go
复制代码
Let's take a look at the contents of the calc.go
file :
package example
func Add(a, b int) int {
return a + b
}
复制代码
calc_test.go
The corresponding test case can look like this:
package example
import "testing"
func TestAdd(t *testing.T) {
if ans := Add(1, 2); ans != 3 {
t.Errorf("1 + 2 expected be 3, but %d got", ans)
}
if ans := Add(-1, -2); ans != -3 {
t.Errorf("-1 + -2 expected be -3, but %d got", ans)
}
}
复制代码
We can run go test
and all test cases under this package will be executed.
go test
Command introduction
Here we use the go test
command , which will automatically read *_test.go
the file named in the source directory, generate and run the executable file for testing.
The performance test system can give the performance data of the code to help the tester analyze the performance problem.
go test
Parameter Description:
- -bench regexp Execute corresponding benchmarks, for example: -bench=.
- -cover can view coverage
- -run regexp only runs the function matched by regexp, for example: -run Array then executes the function containing the beginning of Array, this parameter supports wildcards
*
, and some regular expressions, for example^
,$
- -v show test details
For example, execute all test cases in a file, and use to -v
display detailed information
$ go test helloworld_test.go
ok command-line-arguments 0.003s
$ go test -v helloworld_test.go
=== RUN TestHelloWorld
--- PASS: TestHelloWorld (0.00s)
helloworld_test.go:8: hello world
PASS
ok command-line-arguments 0.004s
复制代码
Summarize
This article briefly introduces how to write Golang unit tests and go test
the basic usage of , but Golang's unit tests are far from the same, so you must keep learning!