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条)

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题