如何在golang中测试打印到控制台的方法?

Ent*_*rSB -2 unit-testing go

我有下一个结构.

package logger

import "fmt"

type IPrinter interface {
    Print(value string)
}

type ConsolePrinter struct{}

func (cp *ConsolePrinter) Print(value string) {
    fmt.Printf("this is value: %s", value)
}
Run Code Online (Sandbox Code Playgroud)

测试覆盖率说我需要测试ConsolePrinter Print方法.

我该如何报道这种方法?

谢谢.

Ent*_*rSB 8

在@icza 写的评论之后,我在下面写了测试。

func TestPrint(t *testing.T) {
    rescueStdout := os.Stdout
    r, w, _ := os.Pipe()
    os.Stdout = w

    cp := &ConsolePrinter{}
    cp.Print("test")

    w.Close()
    out, _ := ioutil.ReadAll(r)
    os.Stdout = rescueStdout

    if string(out) != "this is value: test" {
        t.Errorf("Expected %s, got %s", "this is value: test", out)
    }
}
Run Code Online (Sandbox Code Playgroud)

我找到了有问题的示例What is the best way to convert byte array to string? .


Joh*_*ith 6

使用Examples传送功能的使用.

不要担心超过100%的测试覆盖率,特别是对于简单直接的功能.

func ExampleHello() {
    fmt.Println("hello")
    // Output: hello
}
Run Code Online (Sandbox Code Playgroud)

额外的好处是examples使用go doc工具在生成的doc中输出.