想要测试Go
代码需要依赖go test
命令,需注意如下事项
- 在包目录内所有测试文件必须以
_test.go
结尾,go build不会把这些测试文件
编译到最终的可执行文件中。 - 在
_test.go
文件中,单元测试函数的名字须以TestXxxx
的形式 - 每个单元测试函数的参数必须为
*testing.T
,参数t
用于报告测试是否失败以及日志信息。
func TestAdd(t *testing.T) {}
func TestSum(t *testing.T) {}
testing.T参数
的拥有的方法如下:
func (c *T) Error(args ...interface{})
func (c *T) Errorf(format string, args ...interface{})
func (c *T) Fail()
func (c *T) FailNow()
func (c *T) Failed() bool
func (c *T) Fatal(args ...interface{})
func (c *T) Fatalf(format string, args ...interface{})
func (c *T) Log(args ...interface{})
func (c *T) Logf(format string, args ...interface{})
func (c *T) Name() string
func (t *T) Parallel()
func (t *T) Run(name string, f func(t *T)) bool
func (c *T) Skip(args ...interface{})
func (c *T) SkipNow()
func (c *T) Skipf(format string, args ...interface{})
func (c *T) Skipped() bool
go test 参数
- -bench regexp 执行相应的 benchmarks,例如 -bench= (基准测试)
- -cover 开启测试覆盖率
- -run regexp 只运行 regexp 匹配的函数,例如 -run=Array 那么就执行包含有 Array 开头的函数;
- -v 显示测试的详细命令
Hello案例
hello.go
文件
package hello
import "fmt"
func Hello() string {
return "Hello, world"
}
hello_test.go
文件
package hello
import "testing"
func TestHello(t *testing.T) {
got := Hello()
want := "Hello, world"
if got != want {
t.Errorf("got %q want %q", got, want)
}
}
go test -v
=== RUN TestHello
--- PASS: TestHello (0.00s)
PASS
ok project/Go-Note/test/hello 3.481s
测试覆盖率
测试覆盖率是你的代码被测试套件覆盖的百分比,通常我们使用的都是语句的覆盖率,也就是在测试中至少被运行一次的代码占总代码的比例。Go提供内置功能来检查你的代码覆盖率。我们可以使用**go test -cover
**
案例
hello.go
package hello
import "fmt"
func Hello() string {
return "Hello, world"
}
func Add(a, b int) int {
return a + b
}
func PrintInfo() string {
return fmt.Sprintf("hello and this is a test\n")
}
hello_test.go
package hello
import "testing"
func TestHello(t *testing.T) {
got := Hello()
want := "Hello, world"
if got != want {
t.Errorf("got %q want %q", got, want)
}
}
func TestAdd(t *testing.T) {
sum := Add(5, 5)
if sum == 10 {
t.Log("the result is ok")
} else {
t.Fatal("the result is wrong")
}
}
PS D:\syz\study\computer_science\Go\workspaces\src\project\Go-Note\test\hello> go test -v --cover
=== RUN TestHello
--- PASS: TestHello (0.00s)
=== RUN TestAdd
--- PASS: TestAdd (0.00s)
hello_test.go:17: the result is ok
PASS
coverage: 66.7% of statements
ok project/Go-Note/test/hello 0.289s
因为hello_test.go
文件并没有测试PrintInfo()
函数的代码,所以只覆盖了三分之二。