在Go中进行单元测试主要有以下步骤:
-
创建测试文件:
- 测试文件中的命名要求:
- 所有测试文件以_test.go结尾
- e.g.原文件名字为hello_world.go,测试文件为hello_world_test.go
- 另外注意,go文件的建议命名采用全小写字母和下划线的组合的模式
- e.g.原文件名字为hello_world.go,测试文件为hello_world_test.go
- 测试函数为TestXxx (*testing.T)
- 所有测试文件以_test.go结尾
- 测试文件中的命名要求:
-
编写测试文件的代码:
- 以下以返回"hello world"为例
- 原文件:hello_world.go
package helloworld func PrintHelloWorld () string { return "hello world" } - 测试文件:hello_world_test.go
package helloworld import ( "testing" ) func TestPrintHelloWorld (t *testing.T) { expect := "hello world" output := PrintHelloWorld () if expect != output { t.Errorf ("Expect %s do not match actual %s", expect, output) } }
- 原文件:hello_world.go
- 几个细节:
- 要把两个文件放在同一个目录下
- 在测试文件中需要调用原文件的package
- 注意package的命名最好也采用全小写
- 需要import ("testing")
- 以下以返回"hello world"为例