方法很简单,使用go自带的测试框架,新建一个以 _test.go结尾的文件或者修改你原来的文件以_test.go结尾 , 然后将函数名称修改为以 TestXxx(t *testing.T) 或者以 ExampleXxx开头的名称 Xxx为你原来的函数名后神奇的事情就出现了, 在你的函数上方就会出现 run test | run debug按钮 直接点一下就运行或者debug你的代码了。
TestXxx示例
ExampleXxx 运行示例
单元测试用例
TestXxx和 ExampleXxx使用示例
这2种方法的区别在于Test需要带上参数 t *testing.T 而ExampleXxx则不需要, 带参数的TestXxx可以调用 t里面的一系列方法
他们都可以使用Output来指定期望的输出
testing官方手册 https://pkg.go.dev/testing
测试运行命令
这个是命令行运行的,适合批量测试,如果是单个的方法,直接点函数上面的按钮即可
go test -run ” # Run all tests.
go test -run Foo # Run top-level tests matching "Foo", such as "TestFooBar".
go test -run Foo/A= # For top-level tests matching "Foo", run subtests matching "A=".
go test -run /A=1 # For all top-level tests, run subtests matching "A=1".
go test -fuzz FuzzFoo # Fuzz the target matching "FuzzFoo"
Test示例代码
// 使用 TestXxx语法进行测试
func TestSpeechDemo(t *testing.T) {
p1 := &Person{Name: "John", Age: 18}
SpeechDemo(p1) // 这里需要自己判断测试是否通过 如果未通过使用 t.Fatalf来格式化输出异常信息(或者函数抛异常也会是失败), 否则使用 t.Logf
t.Fatal("测试失败") //直接指定这个测试是失败的 这时就会输出所有的控制台结果 包括被测试对象中使用fmt.Print打印的结果
t.Log("abc ok")
// 点击函数上方的 run test 这个会输出以下信息
// go test -timeout 30s -run ^TestSpeechDemo$ tekin.cn/golearn/src/interface/genric_args
// John正在演讲
// John正在游泳
// --- FAIL: TestSpeechDemo (0.00s)
//
// /xxx/golang_learn_mod/src/interface/genric_args/person_test.go:29: 测试失败
//
// FAIL
// FAIL tekin.cn/golearn/src/interface/genric_args 0.281s
// FAIL
}
Example示例代码
// 使用 ExampleXxx方法进行测试
func ExampleSpeechDemo2() {
p := &Person{Name: "Alex", Age: 20}
SpeechDemo2(p)
// output:Alex正在演讲
// Alex正在考试
}