为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
一只斗牛犬 2023-07-31 15:41:11
我正在开发一个小型 CLI 应用程序。我正在尝试编写单元测试。fmt.Println我有一个函数,可以使用/将一些输出作为表格呈现到命令行fmt.Printf。我想知道如何在单元测试中捕获该输出以确保我得到预期的结果?下面只是一个准系统,在某种程度上代表了我想要实现的目标。main.gopackage mainimport (    "fmt"    "io")func print() {    fmt.Println("Hello world")}func main() {    print()}main_test.gopackage mainimport "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? 但运气微乎其微,但这可能是由于我的误解造成的。
查看完整描述

1 回答

?
慕码人8056858

TA贡献1803条经验 获得超6个赞

你必须以某种方式注入目标作家。


你的 API 不够充分,因为它不允许注入。


在此修改后的代码中,目标编写器作为参数给出,但其他 API 实现决策也是可能的。


package main


import (

    "fmt"

    "io"

)


func print(dst io.Writer) {

    fmt.Fprintln(dst, "Hello world")

}


func main() {

    print(os.Stdout)

}

你可以测试这样做


package main


import "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


查看完整回答
反对 回复 2023-07-31
  • 1 回答
  • 0 关注
  • 68 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信