Skip to content

Instantly share code, notes, and snippets.

@xin053
Last active August 30, 2019 04:06
Show Gist options
  • Select an option

  • Save xin053/621dd48dadf48ebc40093e0925d3315d to your computer and use it in GitHub Desktop.

Select an option

Save xin053/621dd48dadf48ebc40093e0925d3315d to your computer and use it in GitHub Desktop.
[go test] go test #go #test

Example

  • 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 errors

errors_test.go

package errors_test

export_test.go

有时候测试包需要使用包中的一些私有元素,那么可以在 export_test.go 中专门导出这些元素给测试用,例如标准库 fmtexport_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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment