Golang测试标准输出

5

我在尝试测试一些打印 ANSI 转义码的函数,例如:

// Print a line in a color
func PrintlnColor(color string, a ...interface{}) {
    fmt.Print("\x1b[31m")
    fmt.Print(a...)
    fmt.Println("\x1b[0m")
}

我试着使用示例来做这件事,但它们似乎不喜欢转义代码。

有没有办法测试写入标准输出的内容?


测试标准输出的目的是什么?在将输出写入标准输出之前,验证函数是否产生所需的输出要容易得多。 - JimB
问题在于stdout是唯一的输出。该函数将返回n int,err error,就像fmt.Println一样。 - giodamelio
你可以将 os.Stdout 替换为类似于返回 *os.Fileio.MultiWriter,但是重构代码以使其可测试更容易。您不需要测试 fmt.Printlnos.Stdout,它们有自己的单元测试。 - JimB
1
写一个 FprintlnColor,然后让 PrintlnColorStdout 调用它。它可以为测试写入到 bytes.Buffer - twotwotwo
1个回答

13

使用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语言编程体验。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接