使用 testing 进行单元测试
golang 的测试库 testing
测试文件与被测试文件在同一个包中
测试文件名为被测试文件名 (去后缀)_test.go
测试用例函数以 Test 开头, TestFunc1(t *testing.T)
一个测试用例文件中可以有多个测试用例函数
在测试用例函数中调用被测试函数, 根据函数返回结果与预期的正确结果的比较,
判断函数是否正确. t.Log 输出日志, t.Fatal 输出错误信息.
执行测试文件的方式
执行全部测试文件中全部函数 go test 如果需要输出日志信息 go test -v
测试单个文件
go test -v xxx_test.go xxx.go
测试单个方法 go test -v -test.run TestFunc1
- // 测试文件 bt_test.go
- package goo
- import "testing"
- func TestFunc1(t *testing.T) {
- result := Addto(100)
- if result == 5050 {
- t.Log("结果正确")
- } else {
- t.Fatal("结果有误")
- }
- }
- // 被测试文件 bt.go
- package goo
- func Func1(n int) int {
- if n == 1 {
- return 1
- } else if n <= 0 {
- return -1
- } else {
- return Func1(n-1) + n
- }
- }
- // 执行结果
- === RUN TestAddto
- --- PASS: TestAddto (0.00s)
bt_test.go:8: 结果正确
PASS
来源: http://www.bubuko.com/infodetail-2947690.html