如何对 CLI 输出进行单元测试

我正在开发一个小型 CLI 应用程序。我正在尝试编写单元测试。fmt.Println我有一个函数,可以使用/将一些输出作为表格呈现到命令行fmt.Printf。我想知道如何在单元测试中捕获该输出以确保我得到预期的结果?下面只是一个准系统,在某种程度上代表了我想要实现的目标。


main.go


package main


import (

    "fmt"

    "io"

)


func print() {

    fmt.Println("Hello world")

}


func main() {

    print()

}

main_test.go


package main


import "testing"


func TestPrint(t *testing.T) {

    expected := "Hello world"

    print() // somehow capture the output

    // if got != expected {

    //  t.Errorf("Does not match")

    // }

}


我尝试了几种方法,例如How to check a log/output in go test? 但运气微乎其微,但这可能是由于我的误解造成的。


一只斗牛犬
浏览 71回答 1
1回答

慕码人8056858

你必须以某种方式注入目标作家。你的 API 不够充分,因为它不允许注入。在此修改后的代码中,目标编写器作为参数给出,但其他 API 实现决策也是可能的。package mainimport (    "fmt"    "io")func print(dst io.Writer) {    fmt.Fprintln(dst, "Hello world")}func main() {    print(os.Stdout)}你可以测试这样做package mainimport "testing"func TestPrint(t *testing.T) {    expected := "Hello world"    var b bytes.Buffer        print(&b) // somehow capture the output    // if b.String() != expected {    //  t.Errorf("Does not match")    // }}bytes.Buffer实现io.Writer并可以用作存根来捕获执行结果。https://golang.org/pkg/bytes/#Buffer
打开App,查看更多内容
随时随地看视频慕课网APP