实现这个测试助手函数有什么重大缺陷吗?
我知道,首选的方法(重构)只会使要测试的函数返回其值并将打印委托给另一个部分,但有时必须测试其中的内容。
import (
"io"
"os"
)
// captureStdout calls a function f and returns its stdout side-effect as string
func captureStdout(f func()) string {
// return to original state afterwards
// note: defer evaluates (and saves) function ARGUMENT values at definition
// time, so the original value of os.Stdout is preserved before it is changed
// further into this function.
defer func(orig *os.File) {
os.Stdout = orig
}(os.Stdout)
r, w, _ := os.Pipe()
os.Stdout = w
f()
w.Close()
out, _ := io.ReadAll(r)
return string(out)
}package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}package main
import (
"io"
"os"
"testing"
)
func Test_main(t *testing.T) {
want := "Hello, World!\n"
got := captureStdout(main)
if got != want {
t.Errorf("main() = %v, want %v", got, want)
}
}
// captureStdout calls a function f and returns its stdout side-effect as string
func captureStdout(f func()) string {
// return to original state afterwards
// note: defer evaluates (and saves) function ARGUMENT values at definition
// time, so the original value of os.Stdout is preserved before it is
// changed further into this function.
defer func(orig *os.File) {
os.Stdout = orig
}(os.Stdout)
r, w, _ := os.Pipe()
os.Stdout = w
f()
w.Close()
out, _ := io.ReadAll(r)
return string(out)
}发布于 2023-01-10 04:52:04
r, w, \_ := os.Pipe()
为什么我们忽略错误返回?我们真的相信没有办法让管道失效吗?即使在一堆打开的()S没有关闭()?
out, \_ := io.ReadAll(r)
更令人费解的是。阅读错误永远不会发生吗?
对不起,我不能建议以当前状态传送此代码。
https://codereview.stackexchange.com/questions/282374
复制相似问题