我在尝试测试一些打印 ANSI 转义码的函数,例如:
// Print a line in a color
func PrintlnColor(color string, a ...interface{}) {
fmt.Print("\x1b[31m")
fmt.Print(a...)
fmt.Println("\x1b[0m")
}
我试着使用示例来做这件事,但它们似乎不喜欢转义代码。
有没有办法测试写入标准输出的内容?
我在尝试测试一些打印 ANSI 转义码的函数,例如:
// Print a line in a color
func PrintlnColor(color string, a ...interface{}) {
fmt.Print("\x1b[31m")
fmt.Print(a...)
fmt.Println("\x1b[0m")
}
我试着使用示例来做这件事,但它们似乎不喜欢转义代码。
有没有办法测试写入标准输出的内容?
使用fmt.Fprint
将内容打印到io.Writer
中,可以控制输出的位置。
var out io.Writer = os.Stdout
func main() {
// write to Stdout
PrintlnColor("foo")
buf := &bytes.Buffer{}
out = buf
// write to buffer
PrintlnColor("foo")
fmt.Println(buf.String())
}
// Print a line in a color
func PrintlnColor(a ...interface{}) {
fmt.Fprint(out, "\x1b[31m")
fmt.Fprint(out, a...)
fmt.Fprintln(out, "\x1b[0m")
}
点击这里进行Go语言编程体验。
n int,err error
,就像fmt.Println
一样。 - giodamelioos.Stdout
替换为类似于返回*os.File
的io.MultiWriter
,但是重构代码以使其可测试更容易。您不需要测试fmt.Println
和os.Stdout
,它们有自己的单元测试。 - JimBFprintlnColor
,然后让PrintlnColor
用Stdout
调用它。它可以为测试写入到bytes.Buffer
。 - twotwotwo