为什么需要测试
完善的测试体系可以提高开发效率。如果你的项目足够复杂,有两种有效的方法可以尽可能减少错误:代码审查和测试。 Go语言为实现单元提供了测试包。测试功能。
测试规则
要开始单元测试,您需要准备一个go源代码文件。命名文件时,文件名必须以_test.go结尾。一个单元测试源代码文件可以由多个测试用例组成(理解如下): function),并且每个测试用例名称必须以 Test 为前缀。例如:
func TestXxx( t *testing.T ){
//……
}
编写测试用例时,应记住以下几点:
- 测试用例文件不参与正常的源代码编译,也不包含在可执行文件中。
- 测试用例文件名必须以
_test.go结尾。 - 要导入测试包,必须使用 import。
- 测试函数名称以
Test或Benchmark开头,后跟任意字符串。但是,第一个字母必须大写(例如 TestAbc())。一个测试用例文件可以包含多个测试函数。 - 单元测试使用
(t *testing.T)作为参数,性能测试使用(t *testing.B)作为参数。 - 使用
go test命令执行测试用例文件。 main() 函数不需要作为源代码的入口点。源代码文件中所有以Test开头、以_test.go结尾的函数都会自动执行。
Go语言测试包提供了三种测试方法:单元(功能)测试、性能(压力)测试和覆盖率测试。
单元(功能)测试
在同一文件夹下创建两个Go语言文件,分别命名为demo.go和demt_test.go,如下图所示。
具体代码如下。
演示.go:
package demo
//長さと幅から面積を取得
func GetArea(weight int、height int) int {
return weight * height
} 演示_测试.go:
package demo
import "testing"
func TestGetArea(t *testing.T) {
area := GetArea(40, 50)
if area != 2000 {
t.Error("テスト失敗")
}
} 运行测试命令,结果如下:
PS D:\code> go test -v
=== RUN TestGetArea
— PASS: TestGetArea (0.00s)
PASS
ok _/D_/code 0.435s
性能(压力)测试
修改demo_test.go中的代码如下:
package demo
import "test"
func BenchMarkGetArea(t *test。B){
for i:= 0; i <t.N; i ++ {
GetArea(40,50)
}
} 运行测试命令,结果如下:
PS D:\code> go test -bench=”.”
goos: windows
goarch: amd64
BenchmarkGetArea-4 2000000000 0.35 ns/op
PASS
ok _/D_/code 1.166s
上述信息显示,该程序运行了2000000000次,总共耗时0.35纳秒。

覆盖率测试可以让你知道测试程序覆盖了多少业务代码(即demo_test.go中测试了demo.go中的多少代码),如果可能的话100%覆盖最好。
修改demo_test.go代码如下:
package demo
import "test"
func TestGetArea(t * testing.T){
area:= GetArea(40,50)
if area!= 2000 {
t.Error("テストに失敗しました")
}
}
func BenchMarkGetArea(t * testing.B){
for i:= 0; i <t.N; i ++ {
GetArea(40,50)
}
} 运行测试命令,结果如下:
PS D:\code> go test -cover
PASS
coverage: 100.0% of statements
ok _/D_/code 0.437s




![2021 年如何设置 Raspberry Pi Web 服务器 [指南]](https://i0.wp.com/pcmanabu.com/wp-content/uploads/2019/10/web-server-02-309x198.png?w=1200&resize=1200,0&ssl=1)

