如何在Go单元测试中测试函数的输出(stdout / stderr) [英] How to test a function's output (stdout/stderr) in Go unit tests
问题描述
func(t * Thing)print(min_verbosity int,message string ){
如果t.verbosity> = minv {
fmt.Print(message)
}
}
但是,我怎样才能测试函数实际发送到标准输出? 测试::输出做我的想在Perl中。我知道我可以写所有我自己的样板文件在Go中执行相同的操作(如此处所述):
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!)
}
但是对于每一项测试来说,这都是额外的工作。我希望有一个更标准的方法,或者可能是一个抽象库来处理这个问题。
有一点还要记住,例如我有一个命令行应用程序,它使用 log
我写了这个函数:
$ b $ pre $ 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(删除的证书www.example。 com \\\
,output)
使用这个断言库:http://godoc.org/github.com/stretchr/testify/assert 。
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.
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\n", output)
Using this assert library: http://godoc.org/github.com/stretchr/testify/assert.
这篇关于如何在Go单元测试中测试函数的输出(stdout / stderr)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!