如何在单元测试中测试功能的输出(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/担架/证明/声明.