go test 使用

  • 2019-03-31
  • 浏览 (1420)

go test 是 golang 提供的测试命令,它会在 *_test.go 中寻找 test 测试、benchmark 基准 和 examples 示例 函数。测试函数必须以 TestXXX 的函数名出现(XXX 为以非小写字母开头),基准函数必须以 BenchmarkXXX 的函数名出现,示例函数必须以 ExampleXXX 的形式

规则:

1. 文件名须以"_test.go"结尾

2. test测试的方法名须以"Test"打头,并且形参为 (t *testing.T)

3. benchmark测试的方法名须以"Benchmark"打头,并且形参为 (t *testing.T)

4. example测试的方法名须以"Test"打头,并且形参为 (t *testing.T),示例函数无需接收参数,但需要使用注释的 Output: 标记说明示例函数的输出值,未指定Output:标记或输出值为空的示例函数不会被执行。

5. 测试函数中的某条测试用例执行结果与预期不符时,调用t.Error()t.Errorf()方法记录日志并标记测试失败

// test 测试函数
func TestXXX(t *testing.T) { ... }

// benchmark 基准函数
func BenchmarkXXX(b *testing.B) { ... }

// examples 示例函数
func ExamplePrintln() {

    Println("this is an example.")

    //Output:this is an example.

}

举例

文件名:/hello_test.go

package main

import (
    "testing"
    "fmt"
)

func TestHello(t *testing.T) {
    fmt.Println("TestHello")
}

func TestWorld(t *testing.T) {
    fmt.Println("TestWorld")
}

测试整个文件:`go test -v hello_test.go`

=== RUN TestHello
TestHello
--- PASS: TestHello (0.00s)
=== RUN TestWorld
TestWorld
--- PASS: TestWorld (0.00s)
PASS
ok     command-line-arguments  0.007s

测试单个函数:`go test -v hello_test.go -test.run TestHello`

=== RUN TestHello
TestHello
--- PASS: TestHello (0.00s)
PASS
ok     command-line-arguments  0.008s
0  赞