Go语言之单元测试

单元测试

Go 标准库中有一个叫做 testing 的测试框架, 可以用于单元测试和性能测试.

它是和命令 go test 集成使用的.

测试文件是以后缀 _test.go 命名的, 通常和被测试的文件放在同一个包中.

注意

  1. 测试文件必须以后缀 _test.go 命名的

  2. 测试方法要以Test开头

  3. go test后面可以指定文件也可以指定文件夹

  4. 测试方法无Error则不会打印代码过程中的输出信息,添加上-v就可以了,并且会显示正在测试的方法

    测试方法有Error则会打印代码过程中的输出信息,添加上-v则会显示正在测试的方法

我们在test文件夹下创建两个测试文件

str_test.go

1
2
3
4
5
6
7
8
9
10
11
package test

import (
"fmt"
"testing"
)

// 普通的测试
func Test01(t *testing.T) {
fmt.Println("结果1")
}

str2_test.go

1
2
3
4
5
6
7
8
9
10
11
12
package test

import (
"fmt"
"testing"
)

// 普通的测试
func Test02(t *testing.T) {
fmt.Println("结果2")
t.Error("这是错误信息")
}

分别运行测试

1
2
3
4
go test ./test/str_test.go
go test -v ./test/str_test.go
go test ./test/str2_test.go
go test -v ./test/

结果分别是

测试1结果

ok command-line-arguments 0.327s

测试2结果

=== RUN Test01
结果1
— PASS: Test01 (0.00s)
PASS
ok command-line-arguments 0.244s

测试3结果

结果2
— FAIL: Test02 (0.00s)
str2_test.go:11: 这是错误信息
FAIL
FAIL command-line-arguments 0.317s
FAIL

测试4结果

=== RUN Test02
结果2
str2_test.go:11: 这是错误信息
— FAIL: Test02 (0.00s)
=== RUN Test01
结果1
— PASS: Test01 (0.00s)
FAIL
FAIL ZDevOpsGo/test 0.281s
FAIL