testing包提供了在Go中实现基本的自动测试的能力,go没有强制要求文件名,但一般测试文件名会与被测试文件的名加上_test.go后缀结尾,并且测试文件和被测试文件必须位于一个包内。测试函数一般是Test开头,参数为(*testing.T)
先看被测试的源代码,这个功能就是结构体转换成json格式字符串。
package main
import (
"encoding/json"
"log"
)
type Person struct {
Name string `json:"name,omitempty"`
Age int `json:"age,omitempty"`
}
func Decode() string {
p := Person{
Name: "George",
Age: 40,
}
jsonByteData, err := json.Marshal(p)
if err != nil {
log.Fatal(err)
}
jsonStringData := string(jsonByteData)
return jsonStringData
}
func main() {
Decode()
}
测试代码
package main
import (
"testing"
)
func TestDecode(t *testing.T) {
code := Decode()
if code != `{"name":"George","age":40}` {
t.Error("error", code)
}
}
在代码目录下执行go test,输出下面代表测试成功
PASS
ok gin/src/testing 0.468s
如果失败,输出错误的方法,还会打印错误日志
--- FAIL: TestDecode (0.00s)
t_test.go:10: error {"name":"George","age":40}
FAIL
exit status 1
FAIL gin/src/testing 0.383s