英文:
How to test io.writer in golang?
问题
最近我希望为Golang编写一个单元测试。函数如下所示。
func (s *containerStats) Display(w io.Writer) error {
fmt.Fprintf(w, "%s %s\n", "hello", "world")
return nil
}
那么我该如何测试 "func Display" 的结果是否为 "hello world"?
英文:
Recently I hope to write a unit test for golang. The function is as below.
func (s *containerStats) Display(w io.Writer) error {
fmt.Fprintf(w, "%s %s\n", "hello", "world")
return nil
}
So how can I test the result of "func Display" is "hello world"?
答案1
得分: 33
您可以简单地传入自己的io.Writer
,并测试写入其中的内容是否与您期望的相匹配。bytes.Buffer
是一个很好的选择,因为它只是将输出存储在其缓冲区中。
func TestDisplay(t *testing.T) {
s := newContainerStats() // 将此处替换为适当的构造函数
var b bytes.Buffer
if err := s.Display(&b); err != nil {
t.Fatalf("s.Display() 出错: %s", err)
}
got := b.String()
want := "hello world\n"
if got != want {
t.Errorf("s.Display() = %q,期望 %q", got, want)
}
}
英文:
You can simply pass in your own io.Writer
and test what gets written into it matches what you expect. bytes.Buffer
is a good choice for such an io.Writer
since it simply stores the output in its buffer.
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论