doumaojin4008 2014-11-07 15:33
浏览 184
已采纳

如何在Go单元测试中测试功能的输出(stdout / stderr)

I have a simple function I want to test:

func (t *Thing) print(min_verbosity int, message string) {
    if t.verbosity >= minv {
        fmt.Print(message)
    }
}

But how can I test what the function actually sends to standard output? Test::Output does what I want in Perl. I know I could write all my own boilerplate to do the same in Go (as described here):

orig = os.Stdout
r,w,_ = os.Pipe()
thing.print("Some message")
var buf bytes.Buffer
io.Copy(&buf, r)
w.Close()
os.Stdout = orig
if(buf.String() != "Some message") {
    t.Error("Failure!")
}

But that's a lot of extra work for every single test. I'm hoping there's a more standard way, or perhaps an abstraction library to handle this.

  • 写回答

3条回答 默认 最新

  • dongmi3203 2014-11-07 16:50
    关注

    One thing to also remember, there's nothing stopping you from writing functions to avoid the boilerplate.

    For example I have a command line app that uses log and I wrote this function:

    func captureOutput(f func()) string {
        var buf bytes.Buffer
        log.SetOutput(&buf)
        f()
        log.SetOutput(os.Stderr)
        return buf.String()
    }
    

    Then used it like this:

    output := captureOutput(func() {
        client.RemoveCertificate("www.example.com")
    })
    assert.Equal("removed certificate www.example.com
    ", output)
    

    Using this assert library: http://godoc.org/github.com/stretchr/testify/assert.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿