当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > Go单元测试注意事项及测试单个方法和整个文件的命令

Go单元测试注意事项及测试单个方法和整个文件的命令

2018年08月02日  | 移动技术网IT编程  | 我要评论

Go程序开发过程中免不了要对所写的单个业务方法进行单元测试,Go提供了 “testing” 包可以实现单元测试用例的编写,不过想要正确编写单元测试需要注意以下三点:

  • Go文件名必须以 "_test" 结尾
  • Go文件中的方法名必须以 “Test” 打头
  • 方法的形参必须为 (t *testing.T)

以下是我写的一个unit_test.go单元测试文件

package test

import (
    "testing"
    "fmt"
)

// 测试helloworld
func TestHelloWorld(t *testing.T) {
    fmt.Println("This is a HelloWorld unit test")
}

// 测试控制台打印
func TestPrint(t *testing.T) {
    fmt.Println("This is a Print unit test")
}

测试整个文件命令如下:

$ go test -v unit_test.go

结果如下:

=== RUN   TestHelloWorld
This is a HelloWorld unit test
--- PASS: TestHelloWorld (0.00s)
=== RUN   TestPrint
This is a Print unit test
--- PASS: TestPrint (0.00s)
PASS
ok      command-line-arguments  0.005s

测试单个方法命令如下:

$ go test -v unit_test.go -test.run TestHelloWorld

结果如下:

=== RUN   TestHelloWorld
This is a HelloWorld unit test
--- PASS: TestHelloWorld (0.00s)
PASS
ok      command-line-arguments  0.003s

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网