How to test io.writer in golang?

huangapple go评论81阅读模式
英文:

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)
	}
}

huangapple
  • 本文由 发表于 2015年4月8日 10:27:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/29504852.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定