gpt4 book ai didi

testing - 如何在单元测试中测试函数的输出(stdout/stderr)

转载 作者:IT老高 更新时间:2023-10-28 13:04:58 26 4
gpt4 key购买 nike

我想测试一个简单的函数:

func (t *Thing) print(min_verbosity int, message string) {
if t.verbosity >= minv {
fmt.Print(message)
}
}

但是我怎样才能测试函数实际发送到标准输出的内容呢? Test::Output在 Perl 中做我想要的。我知道我可以编写自己的所有样板在 Go 中做同样的事情(如 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!")
}

但是对于每一个测试来说,这都是很多额外的工作。我希望有一种更标准的方法,或者可能是一个抽象库来处理这个问题。

最佳答案

还有一点要记住,没有什么能阻止你编写函数以避免样板。

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

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/stretchr/testify/assert .

关于testing - 如何在单元测试中测试函数的输出(stdout/stderr),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26804642/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com