Go学习:测试

      对于测试有一句比较有名的口号: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 .
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

.番茄炒蛋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值