如何在单元测试中测试功能的输出(stdout/stderr) [英] How to test a function's output (stdout/stderr) in unit tests

查看:40
本文介绍了如何在单元测试中测试功能的输出(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)
    }
}

但是我如何测试该函数实际发送到标准输出的内容呢? Test :: Output 可以满足我的要求在Perl中.我知道我可以编写自己的所有样板以在Go中执行相同的操作(如此处所述):

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.

推荐答案

还要记住一件事,没有什么可以阻止您编写函数来避免样板.

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

例如,我有一个使用log的命令行应用程序,并且我编写了以下函数:

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()
}

然后像这样使用它:

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

使用此断言库: http://godoc.org/github.com/担架/证明/声明.

这篇关于如何在单元测试中测试功能的输出(stdout/stderr)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆