最近我希望为golang写一个单元测试.功能如下.
func (s *containerStats) Display(w io.Writer) error {
fmt.Fprintf(w, "%s %s\n", "hello", "world")
return nil
}
Run Code Online (Sandbox Code Playgroud)
那么如何测试"func Display"的结果是"hello world"?
Pau*_*kin 19
您可以简单地传递自己的内容,io.Writer并测试写入内容的内容是否符合您的预期.bytes.Buffer这是一个很好的选择,io.Writer因为它只是将输出存储在其缓冲区中.
func TestDisplay(t *testing.T) {
s := newContainerStats() // Replace this the appropriate constructor
var b bytes.Buffer
if err := s.Display(&b); err != nil {
t.Fatalf("s.Display() gave error: %s", err)
}
got := b.String()
want := "hello world\n"
if got != want {
t.Errorf("s.Display() = %q, want %q", got, want)
}
}
Run Code Online (Sandbox Code Playgroud)