[TOC]
test 输出友好的三个因素
- why the test exists:为什么要测试
- what’s being tested:什么将要被测试
- the result of the test in clear complete sentences that are easy to read: 测试的结果简单易懂
- 能达到这三个效果的测试框架:https://github.com/stretchr/testify/
testing
- t.Log: 测试的输出
- t.Logf:
go test -v
时都会输出 - t.Fatal & t.Fatalf 作用:
- 告知testing framework 测试失败
- 输出测试失败的消息
- 结束该测试函数
- t.Error & t.Errorf: 输出异常消息,不结束该测试
- 如果一个测试函数中没调用t.Error 与 t.Fatal,测试视为通过
- 常用命令:
go test -v -run="xxx"
go test -v
- 测试当前目录下以及子目录的测试:
go test ./...
- 模式匹配:
go test foo/...
orgo test foo...
Benchmark
- 执行loop前要调用:
b.ResetTimer()
-
go test -v -run="none" -bench="BenchmarkXXX" -benchtime="3s" -benchmem
-
-run
与-Benchmark
支配通配符匹配 -
-benchmem
显示内存信息
-
go test -v -run="none" -bench=. -benchtime="3s" -benchmem
输出的含义
-
allocs/op
: 每个操作 heap 申请的个数 -
B/op
: 每个操作申请的bytes
测试框架 testify
原理类似testing。主要有两个库,类比关系如下
- t.ErrorX --> assert.Equal(t, 123, 123, "they should be equal")测试失败,继续测试其他
- t.FatalX --> require.Equal(123, 123, "they should be equal") 测试失败马上停止测试
- 常用的assert:
- assert.Equal()/ NotEqual()
- assert.NotError()
- demo