go test 工具详解

在学习如何编写测试代码之前,需要先了解一下Go 提供的测试工具 :go test

go test 本身可以携带很多的参数,熟悉这些参数,可以让我们的测试过程更加方便。

下面就根据场景来解释一下常用的几个参数:

1、运行整个项目的测试文件

$ go test
PASS
ok      _/home/wangbm/golang/math   0.003s

2、只运行某个测试文件( math_test.go, math.go 是一对,缺一不可,前后顺序可对调)

$ go test math_test.go math.go
ok      command-line-arguments  0.002s

3、加 -v 查看详细的结果

$ go test math_test.go math.go
=== RUN   TestAdd
    TestAdd: main_test.go:22: the result is ok
    TestAdd: main_test.go:22: the result is ok
    TestAdd: main_test.go:22: the result is ok
    TestAdd: main_test.go:22: the result is ok
    TestAdd: main_test.go:22: the result is ok
--- PASS: TestAdd (0.00s)
PASS
ok      command-line-arguments  0.003s

4、只测试某个函数,-run 支持正则,如下例子中 TestAdd,如果还有一个测试函数为 TestAdd02,那么它也会被运行。

$ go test -v -run="TestAdd"
=== RUN   TestAdd
    TestAdd: math_test.go:22: the result is ok
    TestAdd: math_test.go:22: the result is ok
    TestAdd: math_test.go:22: the result is ok
    TestAdd: math_test.go:22: the result is ok
    TestAdd: math_test.go:22: the result is ok
--- PASS: TestAdd (0.00s)
PASS
ok      _/home/wangbm/golang/math   0.003s

5、生成 test 的二进制文件:加 -c 参数

$ go test -v -run="TestAdd" -c
$
$ ls -l
total 3208
-rw-r--r-- 1 root root      95 May 25 20:56 math.go
-rwxr-xr-x 1 root root 3272760 May 25 21:00 math.test
-rw-r--r-- 1 root root     525 May 25 20:56 math_test.go

6、执行这个 test 测试文件:加 -o 参数

$ go test -v -o math.test
=== RUN   TestAdd
    TestAdd: math_test.go:22: the result is ok
    TestAdd: math_test.go:22: the result is ok
    TestAdd: math_test.go:22: the result is ok
    TestAdd: math_test.go:22: the result is ok
    TestAdd: math_test.go:22: the result is ok
--- PASS: TestAdd (0.00s)
=== RUN   TestAum
    TestAum: math_test.go:30: 6
--- PASS: TestAum (0.00s)
PASS
ok      _/home/wangbm/golang/math   0.002s

7、只测试安装/重新安装 依赖包,而不运行代码:加 -i 参数

# 这里没有输出
$ go test -i

END 链接