我们在gotest包中创建两个文件,目录结构如下所示:
[GoExpert]
|--[src]
|--[gotest]
|--example.go
|--example_test.go
其中example.go为源代码文件,example_test.go为测试文件。
源代码文件example.go中包含SayHello()、SayGoodbye()和PrintNames()三个方法,如下所示:
package gotest
import "fmt"
// SayHello 打印一行字符串
func SayHello() {
fmt.Println("Hello World")
}
// SayGoodbye 打印两行字符串
func SayGoodbye() {
fmt.Println("Hello,")
fmt.Println("goodbye")
}
// PrintNames 打印学生姓名
func PrintNames() {
students := make(map[int]string, 4)
students[1] = "Jim"
students[2] = "Bob"
students[3] = "Tom"
students[4] = "Sue"
for _, value := range students {
fmt.Println(value)
}
}
这几个方法打印内容略有不同,分别代表一种典型的场景:
测试文件example_test.go中包含3个测试方法,于源代码文件中的3个方法一一对应,测试文件如下所示:
package gotest_test
import "gotest"
// 检测单行输出
func ExampleSayHello() {
gotest.SayHello()
// OutPut: Hello World
}
// 检测多行输出
func ExampleSayGoodbye() {
gotest.SayGoodbye()
// OutPut:
// Hello,
// goodbye
}
// 检测乱序输出
func ExamplePrintNames() {
gotest.PrintNames()
// Unordered output:
// Jim
// Bob
// Tom
// Sue
}
例子测试函数命名规则为"Examplexxx",其中"xxx"为自定义的标识,通常为待测函数名称。
这三个测试函数分别代表三种场景:
注:字符串比较时会忽略前后的空白字符。
命令行下,使用go test或go test example_test.go命令即可启动测试,如下所示:
E:\OpenSource\GitHub\RainbowMango\GoExpertProgrammingSourceCode\GoExpert\src\gotest>go test example_test.go
ok command-line-arguments 0.331s
go test,此时该目录下的其他测试文件也会一并执行;go test <xxx_test.go>,此时仅执行特定文件中的测试函数;