testing - 单元测试
测试用例有四种形式:
TestXxxx(t testing.T) // 基本测试用例
BenchmarkXxxx(b testing.B) // 压力测试的测试用例
Example_Xxx() // 测试控制台输出的例子
TestMain(m *testing.M) // 测试Main函数
gotest的变量有这些:
* test.short : 一个快速测试的标记,在测试用例中可以使用testing.Short()来绕开一些测试
* test.outputdir : 输出目录
* test.coverprofile : 测试覆盖率参数,指定输出文件
* test.run : 指定正则来运行某个/某些测试用例
* test.memprofile : 内存分析参数,指定输出文件
* test.memprofilerate : 内存分析参数,内存分析的抽样率
* test.cpuprofile : cpu分析输出参数,为空则不做cpu分析
* test.blockprofile : 阻塞事件的分析参数,指定输出文件
* test.blockprofilerate : 阻塞事件的分析参数,指定抽样频率
* test.timeout : 超时时间
* test.cpu : 指定cpu数量
* test.parallel : 指定运行测试用例的并行数
testing包内的结构
* B : 压力测试
* BenchmarkResult : 压力测试结果
* Cover : 代码覆盖率相关结构体
* CoverBlock : 代码覆盖率相关结构体
* InternalBenchmark : 内部使用的结构
* InternalExample : 内部使用的结构
* InternalTest : 内部使用的结构
* M : main测试使用的结构
* PB : Parallel benchmarks 并行测试使用结果
* T : 普通测试用例
* TB : 测试用例的接口
func BenchmarkXxx(*testing.B)
func BenchmarkHello(b *testing.B) {
for i := 0; i fmt.Sprintf("hello")
}
}
执行 go test -bench=.,输出:
$ go test -bench=.
BenchmarkFib10-4 3000000 424 ns/op
PASS
ok chapter09/testing 1.724s
基准测试即压力测试
go test -run '' # Run 所有测试。
go test -run Foo # Run 匹配 "Foo" 的顶层测试,例如 "TestFooBar"。
go test -run Foo/A= # 匹配顶层测试 "Foo",运行其匹配 "A=" 的子测试。
go test -run /A=1 # 运行所有匹配 "A=1" 的子测试。
BUG 覆盖率
go test -cover
go tool cover
httptest - HTTP 测试辅助工具
通过 curl 进行简单的测试:
增:curl -i -X POST http://localhost:2017/topic/ -H 'content-type: application/json' -d '{"title":"The Go Standard Library","content":"It contains many packages."}'
查:curl -i -X GET http://localhost:2017/topic/1
改:curl -i -X PUT http://localhost:2017/topic/1 -H 'content-type: application/json' -d '{"title":"The Go Standard Library By Example","content":"It contains many packages, enjoying it."}'
删:curl -i -X DELETE http://localhost:2017/topic/1
通过 httptest 进行测试
https://books.studygolang.com/The-Golang-Standard-Library-by-Example/chapter09/09.6.html
测试 handlePost 函数。
func TestHandlePost(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/topic/", handleRequest)
reader := strings.NewReader(`{"title":"The Go Standard Library","content":"It contains many packages."}`)
r, _ := http.NewRequest(http.MethodPost, "/topic/", reader)
w := httptest.NewRecorder()
mux.ServeHTTP(w, r)
resp := w.Result()
if resp.StatusCode != http.StatusOK {
t.Errorf("Response code is %v", resp.StatusCode)
}
}
还有很多优秀的第三方测试包,比如
https://github.com/stretchr/testify 用于增强 testing 进行单元测试,进行 mock 等,有机会会写文章介绍它的使用;
再比如,https://github.com/onsi/ginkgo 用于集成测试等等。