对于测试有一句比较有名的口号:Debugging Sucks! Testing Rocks! 我们希望我们的程序,多做测试而不是多做调试;我们能否写出一个好的测试,对于一个成功的开发非常重要.同样对于一门语言也非常的重要,因此go语言再测试方面还是有自己的见解的
传统测试 VS 表格驱动测试
传统测试
// 要被测试的方法
public int add(int a, int b) {
return a + b;
}
// 测试方法
@Test
public void testAdd() {
assertEquals(3, add(1, 2));
assertEquals(2, add(0, 2));
assertEquals(0, add(0, 0));
assertEquals(0, add(-1, 1));
assertEquals(Integer.MIN_VALUE, add(1, Integer.MAX_VALUE));
}
传统测试缺点:
- 测试数据和测试逻辑混在一起
- 出错信息不明确
- 一旦一个数据出错测试全部结束
表格驱动测试
测试一(使用编辑器测试)
要被测试的函数
// 求勾股定理
func calcTriangle(a, b int) int {
return int(math.Sqrt(float64((a*a + b*b))))
}
测试函数
func TestCalcTriangle(t *testing.T) {
tests := []struct {
a, b, c int
}{
{3, 4, 5},
{6, 8, 10},
{5, 12, 13},
{7, 24, 25},
}
for _, test := range tests {
triangle := calcTriangle(test.a, test.b)
if triangle != test.c {
t.Errorf("calcTriangle(%d,%d); 期望值:%d 实际值:%d;",
test.a, test.b, test.c, triangle)
}
}
}
正向测试
逆向测试
测试二(使用命令行测试)
要被测试的函数
func add(a, b int) int {
return a + b
}
测试函数
func TestAdd(t *testing.T) {
tests := []struct {
a, b, c int
}{
{1, 2, 3},
{2, 0, 2},
{0, 0, 0},
{-1, 1, 0},
{math.MaxInt64, 1, 1},
}
for _, test := range tests {
triangle := add(test.a, test.b)
if triangle != test.c {
t.Errorf("add(%d,%d); 期望值:%d; 实际值:%d", test.a, test.b, test.c, triangle)
}
}
}
正向测试
逆向测试
使用到的命令:
go test
代码覆盖率
测试一(使用编辑器测试)
查看代码覆盖率使用goland点击Run '…'with Coverage
被覆盖到的代码编辑器会用绿线表示;如果有未覆盖到的会用红线进行表示
测试二(使用命令行测试)
使用到的命令:
go test
go test -coverprofile=c.out
go tool cover -html=c.out
被覆盖到的代码用绿色进行表示;如果有未覆盖到的代码用红色进行表示
性能测试
测试一(使用编辑器测试)
func BenchmarkSqrt(b *testing.B) {
for i := 0; i < b.N; i++ {
sqrt := Sqrt(3, 4)
ans := 5
if sqrt != ans {
b.Errorf("Sqrt(%d,%d); 期望值: %d; 实际值: %d", 3, 4, 5, sqrt)
}
}
}
运行280241043次;4.068 ns/op
测试二(使用命令行测试)
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
add := Add(math.MaxInt64, 1)
ans := math.MinInt64
if add != ans {
b.Errorf("Add(%d,%d); 期望值: %d; 实际值: %d", math.MaxInt64, 1, math.MinInt64, add)
}
}
}
运行1000000000次;0.2482 ns/op
使用到的命令:
go test -bench .