- It needs to be in a file with a name like
xxx_test.go - The test function must start with the word
Test - The test function takes one argument only
t *testing.T
package main
import "testing"
func TestHello(t *testing.T) {
got := Hello()
want := "Hello, world"
if got != want {
t.Errorf("got %q want %q", got, want) // %q 用双引号包裹
}
}测试文件命令: 包名_test.go, 测试文件包名: 包名_test, 例如标准库 errors
errors
package errorserrors_test.go
package errors_test有时候测试包需要使用包中的一些私有元素,那么可以在 export_test.go 中专门导出这些元素给测试用,例如标准库 fmt 的 export_test.go
export_test.go
package fmt
var IsSpace = isSpace
var Parsenum = parsenum示例函数以 Example 为函数开头,并且没有参数和返回值,并且有// Output:格式的注释,测试工具会执行是这个示例函数,然后检测这个示例函数的标准输出和注释是否匹配,并且示例函数会在产生的 doc 中展示, 例如标准库errors中的示例函数
func ExampleNew_errorf() {
const name, id = "bimmler", 17
err := fmt.Errorf("user %q (id %d) not found", name, id)
if err != nil {
fmt.Print(err)
}
// Output: user "bimmler" (id 17) not found
}