源代码目录结构

我们在gotest包中创建两个文件,目录结构如下所示:

  1. [GoExpert]
  2. |--[src]
  3. |--[gotest]
  4. |--example.go
  5. |--example_test.go

其中example.go为源代码文件,example_test.go为测试文件。

源代码文件

源代码文件example.go中包含SayHello()SayGoodbye()PrintNames()三个方法,如下所示:

  1. package gotest
  2. import "fmt"
  3. // SayHello 打印一行字符串
  4. func SayHello() {
  5. fmt.Println("Hello World")
  6. }
  7. // SayGoodbye 打印两行字符串
  8. func SayGoodbye() {
  9. fmt.Println("Hello,")
  10. fmt.Println("goodbye")
  11. }
  12. // PrintNames 打印学生姓名
  13. func PrintNames() {
  14. students := make(map[int]string, 4)
  15. students[1] = "Jim"
  16. students[2] = "Bob"
  17. students[3] = "Tom"
  18. students[4] = "Sue"
  19. for _, value := range students {
  20. fmt.Println(value)
  21. }
  22. }

这几个方法打印内容略有不同,分别代表一种典型的场景:

  • SayHello():只有一行打印输出
  • SayGoodbye():有两行打印输出
  • PrintNames():有多行打印输出,且由于Map数据结构的原因,多行打印次序是随机的。

测试文件

测试文件example_test.go中包含3个测试方法,于源代码文件中的3个方法一一对应,测试文件如下所示:

  1. package gotest_test
  2. import "gotest"
  3. // 检测单行输出
  4. func ExampleSayHello() {
  5. gotest.SayHello()
  6. // OutPut: Hello World
  7. }
  8. // 检测多行输出
  9. func ExampleSayGoodbye() {
  10. gotest.SayGoodbye()
  11. // OutPut:
  12. // Hello,
  13. // goodbye
  14. }
  15. // 检测乱序输出
  16. func ExamplePrintNames() {
  17. gotest.PrintNames()
  18. // Unordered output:
  19. // Jim
  20. // Bob
  21. // Tom
  22. // Sue
  23. }

例子测试函数命名规则为”Examplexxx”,其中”xxx”为自定义的标识,通常为待测函数名称。

这三个测试函数分别代表三种场景:

  • ExampleSayHello(): 待测试函数只有一行输出,使用”// OutPut: “检测。
  • ExampleSayGoodbye():待测试函数有多行输出,使用”// OutPut: “检测,其中期望值也是多行。
  • ExamplePrintNames():待测试函数有多行输出,但输出次序不确定,使用”// Unordered output:”检测。

注:字符串比较时会忽略前后的空白字符。

执行测试

命令行下,使用go testgo test example_test.go命令即可启动测试,如下所示:

  1. E:\OpenSource\GitHub\RainbowMango\GoExpertProgrammingSourceCode\GoExpert\src\gotest>go test example_test.go
  2. ok command-line-arguments 0.331s

总结

  1. 例子测试函数名需要以”Example”开头;
  2. 检测单行输出格式为“// Output: <期望字符串>”;
  3. 检测多行输出格式为“// Output: \ <期望字符串> \ <期望字符串>”,每个期望字符串占一行;
  4. 检测无序输出格式为”// Unordered output: \ <期望字符串> \ <期望字符串>”,每个期望字符串占一行;
  5. 测试字符串时会自动忽略字符串前后的空白字符;
  6. 如果测试函数中没有“Output”标识,则该测试函数不会被执行;
  7. 执行测试可以使用go test,此时该目录下的其他测试文件也会一并执行;
  8. 执行测试可以使用go test <xxx_test.go>,此时仅执行特定文件中的测试函数;