表格测试
Basic_calc
package test
import "math"
func Calc(a, b int) int {
c:=int(math.Sqrt(float64(a*a+b*b)))
return c
}
calc_test
package test
import "testing"
func TestCalc(t *testing.T) {
tests:=[]struct{a,b,c int }{
{3,4,5},
{12,35,37},
{5,12,13},
{8,15,17},
{30000,40000,50000},
}
for _,tt:=range tests{
if actual:=Calc(tt.a,tt.b);actual!=tt.c {
t.Errorf("Error while calc(%d, %d)! Got %d , expected %d",tt.a,tt.b,actual,tt.c)
}
}
}
核心:创建一个Slice,循环测试。相比传统测试(利用assert),具有数据与逻辑分离、代码简洁、容易跟踪多个错误的优点。
- 也可以在测试目录下的目录行中执行
go test .
代码覆盖率
在GoLand中直接测试代码覆盖率,即有多少代码被测试了。
右侧可以查看结果
或者在命令行中,在要测试的目录下
go test -coverprofile=c.out
go tool cover //查看帮助
go tool cover -html=c.out //通过html查看
性能测试
func BenchmarkCalc(b *testing.B) {
/*
Your Prepare work
*/
b.ResetTimer()
for i := 0; i < b.N; i++ {
a:=math.MaxInt8
b:=math.MinInt8
Calc(a,b)
}
}
其中b.N
的值系统会帮我们设定。
例如测试结果
说明每次操作花了0.36ns的时间,总共执行了2000000000次。
- 在命令行中:
go test -bench .
测试更多方面的信息
go test -bench . -cpuprofile cpu.out
查看CPU结果
go tool pprof cpu.out //此时进入交互式命令,可以输入help查看帮助
web //自动弹出网页展示svg图查看结果
注意,如果报错:Failed to execute dot. Is Graphviz installed? Error: exec: "dot": executable file not found in %PATH%
请到http://www.graphviz.org/download/下载Graphviz
, 并配置到环境变量中,将bin目录配置到PATH。
性能优化
根据上述SVG图中节点的大小和线的粗细,可以找到性能瓶颈的地方。
生成文档和示例代码
用注释做文档。
启用一个服务器来在网页上查看文档,例如
godoc -http :6060
可以直接使用go doc
查看文档(注意,此处go和doc分开),或者用go doc YourFun
来查看具体函数的文档
新建一个Queue_test.go文件
package Queue_tool
import "fmt"
type q interface {
Is_Empty() bool
Push(v int)
}
func ExampleQueue_Is_Empty() {
queue:=Queue{}
queue.Push(1)
queue.Push(5)
queue.Push(9)
fmt.Println(queue.Pop())
fmt.Println(queue.Pop())
fmt.Println(queue.Pop())
// Output:
//1
//5
//9
}
其中,最后注释的Output
和结果一定要正确。