Go测试方法
Go测试方法
测试模板
拿取出个位数字例子
- 写数据源numbers
- 写want
- 写got
- want 和 got作比较
代码
// func: FetchUnitsDigit() (int, error)
// aim: 取出个位数字
func FetchUnitsDigit(data interface{}) (int, error) {
toInt64, err := shift.ToInt64(data)
if err != nil {
return 0, err
}
res := toInt64 % 10
return int(res), nil
}
测试代码
func TestFetchUnitsDigit(t *testing.T) {
numbers := 3457.1189
digit, err := FetchUnitsDigit(numbers)
if err != nil {
t.Fatal(err)
}
want := 7
got := digit
if want != got {
t.Errorf("got %d want %d given, %v", got, want, numbers)
}
}
同一个函数相同测试,数据源不同
func TestFetchUnitsDigit(t *testing.T) {
t.Run("测试1", func(t *testing.T) {
numbers := 3457.1189
digit, err := FetchUnitsDigit(numbers)
if err != nil {
t.Fatal(err)
}
want := 7
got := digit
if want != got {
t.Errorf("got %d want %d given, %v", got, want, numbers)
}
})
t.Run("测试2", func(t *testing.T) {
numbers := 33.123
digit, err := FetchUnitsDigit(numbers)
if err != nil {
t.Fatal(err)
}
want := 7
got := digit
if want != got {
t.Errorf("got %d want %d given, %v", got, want, numbers)
}
})
t.Run("测试3", func(t *testing.T) {
numbers := 892
digit, err := FetchUnitsDigit(numbers)
if err != nil {
t.Fatal(err)
}
want := 7
got := digit
if want != got {
t.Errorf("got %d want %d given, %v", got, want, numbers)
}
})
}
压力测试
func BenchmarkFetchUnitsDigit(b *testing.B) {
for i := 0; i < b.N; i++ {
FetchUnitsDigit(4.4441)
}
}