1 回答

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
- 1 回答
- 0 關(guān)注
- 128 瀏覽
添加回答
舉報