dongpi9164 2015-10-26 19:30 采纳率: 0%
浏览 43
已采纳

如何运行没有输出注释的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条回答 默认 最新

  • dqpwdai095465 2015-10-26 20:44
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)