我正在開發一個小型 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
- 1 回答
- 0 關注
- 156 瀏覽
添加回答
舉報
0/150
提交
取消
