第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

如何對 CLI 輸出進行單元測試

如何對 CLI 輸出進行單元測試

Go
一只斗牛犬 2023-07-31 15:41:11
我正在開發(fā)一個小型 CLI 應(yīng)用程序。我正在嘗試編寫單元測試。fmt.Println我有一個函數(shù),可以使用/將一些輸出作為表格呈現(xiàn)到命令行fmt.Printf。我想知道如何在單元測試中捕獲該輸出以確保我得到預(yù)期的結(jié)果?下面只是一個準(zhǔn)系統(tǒng),在某種程度上代表了我想要實現(xiàn)的目標(biāo)。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條經(jīng)驗 獲得超6個贊

你必須以某種方式注入目標(biāo)作家。


你的 API 不夠充分,因為它不允許注入。


在此修改后的代碼中,目標(biāo)編寫器作為參數(shù)給出,但其他 API 實現(xiàn)決策也是可能的。


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實現(xiàn)io.Writer并可以用作存根來捕獲執(zhí)行結(jié)果。


https://golang.org/pkg/bytes/#Buffer


查看完整回答
反對 回復(fù) 2023-07-31
  • 1 回答
  • 0 關(guān)注
  • 128 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號