Circuit in the wall
Circuit in the wall

Reputation: 549

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

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?

Upvotes: 5

Views: 1075

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109416

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

Upvotes: 6

Related Questions