如何运行没有输出注释的 Go 示例?

huangapple go评论98阅读模式
英文:

How to run Go examples, which don't have output comments?

问题

可测试的Go示例看起来很棒。

func ExampleReverse() {
    fmt.Println(stringutil.Reverse("hello"))
    // Output: olleh
}

例如上面的代码等同于一个断言的单元测试:

stringutil.Reverse("hello") == "olleh"

根据golang博客的说法,我们可以编写没有输出注释的示例,但是go testgo test -run ExampleReverse命令只会编译示例而不运行它:

如果我们完全删除输出注释,那么示例函数将被编译但不会被执行。没有输出注释的示例对于演示无法作为单元测试运行的代码非常有用,比如访问网络的代码,同时至少保证示例能够编译通过。

这种示例的输出虽然无法进行测试,但对于用户生成和阅读仍然有用。而示例本身在用户的计算机上运行也很有用。

那么是否有一种方法或工具可以从终端运行*_test.go文件中的示例函数呢?

英文:

Testable Go examples look awesome.

func ExampleReverse() {
    fmt.Println(stringutil.Reverse("hello"))
    // Output: olleh
}

The above, for example, is equivalent to a unit test that asserts:

stringutil.Reverse("hello") == "olleh"

According to the golang blog, we can write examples that don't have an output comment, but then the go test and go test -run ExampleReverse commands only compile the example and don't run it:

> If we remove the output comment entirely then the example function is compiled but not executed. Examples without output comments are useful for demonstrating code that cannot run as unit tests, such as that which accesses the network, while guaranteeing the example at least compiles.

The output of such examples, although not testable, could still be useful for the user to produce and read. And the examples themselves - useful to run on their computer.

So is there a way or a tool that can run example functions in *_test.go files from the terminal?

答案1

得分: 5

你可以从常规的Test*函数中调用Example*函数。

func ExampleOutput() {
    fmt.Println("HEELLO")
}

func TestExampleOutput(t *testing.T) {
    if !testing.Verbose() {
        return
    }
    ExampleOutput()
}

这个示例的主体将显示在文档的Output下面,如果你不想每次都输出,可以通过使用-v标志来限制它的调用。


具体来说,要仅运行你感兴趣的示例,你可以选择:

go test path/to/pkg -run TestExampleOutput -v

或者编译一次,多次运行:

go test path/to/pkg -c
./pkg.test -test.run TestExampleOutput -test.v
英文:

You can call the Example* functions from a regular Test* function.

func ExampleOutput() {
	fmt.Println("HEELLO")
}

func TestExampleOutput(t *testing.T) {
	if !testing.Verbose() {
		return
	}
	ExampleOutput()
}

This body of this example would show up under Output in the docs, and if you don't want the output every time, it's limited to only calling it with the -v flag.


Specifically, to run only the example you're interested in you can either:

go test path/to/pkg -run TestExampleOutput -v

Or to compile once and run multiple times:

go test path/to/pkg -c
./pkg.test -test.run TestExampleOutput -test.v

huangapple
  • 本文由 发表于 2015年10月27日 03:30:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/33354043.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定