【问题标题】:Golang test stdout [duplicate]Golang测试标准输出[重复]
【发布时间】:2015-02-22 22:21:08
【问题描述】:

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

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

我尝试使用Examples 来做,但他们似乎不喜欢转义码。

有什么方法可以测试写入标准输出的内容吗?

【问题讨论】:

  • 测试标准输出的目的是什么?在将其写入标准输出之前验证您的函数是否产生了您想要的输出要容易得多。
  • 问题是 stdout 是唯一的输出。该函数将返回n int, err error,就像fmt.Println
  • 您可以将os.Stdout 替换为类似于返回io.MultiWriter*os.File,但重构代码以使其可测试更容易。你不需要测试fmt.Printlnos.Stdout,它们有自己的单元测试。
  • 是的,写一个FprintlnColor 然后让PrintlnColorStdout 调用它。它可以写信给bytes.Buffer 进行测试。
  • 好的,如果你添加它作为答案,我会接受它。

标签: testing go ansi-escape


【解决方案1】:

使用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")
}

play

【讨论】:

    猜你喜欢
    • 2021-10-20
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 2011-01-11
    相关资源
    最近更新 更多