go测试

表格驱动测试

AddDemo.go

1 // Add to number
2 func Add(a int, b int) int {
3     return a + b
4 }

Add_test.go

 1 import "testing"
 2 // 表格驱动测试
 3 func TestAdd(t *testing.T) {
 4     tests := []struct{ a, b, c int }{
 5         {3, 4, 7},
 6         {1, 2, 3},
 7         {4, 5, 9},
 8         {5, 6, 0},
 9     }
10     for _, tt := range tests {
11         if res := Add(tt.a, tt.b); res != tt.c {
12             t.Errorf("add(%d, %d) ;"+
13                 "got %d; "+
14                 "expected %d ",
15                 tt.a, tt.b, res, tt.c)
16         }
17     }
18 
19 }

由上面的代码可以知道,最后一个测试用例是存在问题的,所以当我们运行测试时,是无法通过测试用例的。

 

 当我们改为正确的值时则可以通过测试

 

posted @ 2021-07-04 11:23  老鲜肉  阅读(61)  评论(0编辑  收藏  举报