Go单元测试命令
Go 语言推荐测试文件和源代码文件放在一块,测试文件以 _test.go 结尾。比如,当前 package 有 calc.go 一个文件,我们想测试 calc.go 中的 Add 和 Mul 函数,那么应该新建 calc_test.go 作为测试文件。 example/ |-- calc.go |--calc_test.go 假如 calc.go 的代码如下: 1 package main 2 3 func Add(a int , b int ) int { 4 return a + b 5 } 6 7 func Mul(a int , b int ) int { 8 return a * b 9 } 那么 calc_test.go 中的测试用例可以这么写: 1 package main 2 3 import "testing" 4 5 func TestAdd(t * testing.T) { 6 if ans := Add(1, 2); ans != 3 { 7 t.Errorf("1 + 2 expected be 3, but %d got" , ans) 8 } 9 10 if ans := Add(-10, -20); ans != -30 { 11 t.Errorf("-10 + -20 expected be -30, but %d got" , ans) 12 }