亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何對 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 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號