可测试的 Go 示例看起来很棒。
func ExampleReverse() {
fmt.Println(stringutil.Reverse("hello"))
// Output: olleh
}
Run Code Online (Sandbox Code Playgroud)
例如,上面的内容相当于断言的单元测试:
stringutil.Reverse("hello") == "olleh"
Run Code Online (Sandbox Code Playgroud)
根据golang 博客,我们可以编写没有输出注释的示例,但是go test和go test -run ExampleReverse命令仅编译示例而不运行它:
如果我们完全删除输出注释,则示例函数将被编译但不会执行。没有输出注释的示例对于演示无法作为单元测试运行的代码(例如访问网络的代码)非常有用,同时保证示例至少可以编译。
此类示例的输出虽然不可测试,但对于用户生成和阅读仍然有用。以及示例本身 - 对于在他们的计算机上运行很有用。
那么有没有一种方法或工具可以从终端运行 *_test.go 文件中的示例函数?
Example*您可以从常规函数中调用这些函数Test*。
func ExampleOutput() {
fmt.Println("HEELLO")
}
func TestExampleOutput(t *testing.T) {
if !testing.Verbose() {
return
}
ExampleOutput()
}
Run Code Online (Sandbox Code Playgroud)
此示例的主体将显示Output在文档中,如果您不想每次都输出,则仅限于仅使用标志调用它-v。
具体来说,要仅运行您感兴趣的示例,您可以:
go test path/to/pkg -run TestExampleOutput -v
Run Code Online (Sandbox Code Playgroud)
或者编译一次并运行多次:
go test path/to/pkg -c
./pkg.test -test.run TestExampleOutput -test.v
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
874 次 |
| 最近记录: |