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

查看:25
本文介绍了如何在单元测试中测试函数的输出 (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
", output)

使用这个断言库:http://godoc.org/github.com/stretchr/testify/assert.

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

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