4.9. 单元测试

Golang单元测试对文件名和方法名,参数都有很严格的要求。

  1. 文件名必须以xx_test.go命名

  2. 方法必须是Test[^a-z]开头

  3. 方法参数必须 t *testing.T

  4. 使用go test执行单元测试

4.9.1. 1.执行单元测试

go_test.go

package main

import "testing"

func TestA(t *testing.T)  {
    t.Log("A")
}

func TestAK(t *testing.T)  {
    t.Log("AK")
}

func TestB(t *testing.T)  {
    t.Log("B")
}

func TestC(t *testing.T)  {
    t.Log("C")
}

func main() {

}
// 指定TestA进行测试,因为支持正则,执行了TestA和TestAK
$ go test -v -run TestA go_test.go
=== RUN   TestA
--- PASS: TestA (0.00s)
    go_test.go:6: A
=== RUN   TestAK
--- PASS: TestAK (0.00s)
    go_test.go:10: AK
PASS
ok      command-line-arguments  0.476s


// 只指定TestA进行测试使用TestA$
$ go test -v -run TestA$ go_test.go
=== RUN   TestA
--- PASS: TestA (0.00s)
    go_test.go:6: A
PASS
ok      command-line-arguments  0.264s

4.9.2. 2.标记单元测试

终止当前测试用例,使用FailNow

package main

import (
    "fmt"
    "testing"
)

func TestFailNow(t *testing.T)  {
    fmt.Println("before fail")
    t.FailNow()
    fmt.Println("after fail")

}
func main() {

}

只标记测试用例,不终止,仍然可以继续执行

package main

import (
    "fmt"
    "testing"
)

func TestFailNow(t *testing.T)  {
    fmt.Println("before fail")
    t.Fail()
    fmt.Println("after fail")

}
func main() {

}
=== RUN   TestFailNow
before fail
after fail
--- FAIL: TestFailNow (0.00s)
FAIL