2015-04-08 02:27
浏览 59


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
", "hello", "world")
    return nil

So how can I test the result of "func Display" is "hello world"?

图片转代码服务由CSDN问答提供 功能建议

最近,我希望为golang编写单元测试。 函数如下所示。

  func(s * containerStats)Display(w io.Writer)error {
  “,” hello“,” world“)

所以我如何测试“ func Display”的结果是“ hello world “?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • duanri1985 2015-04-08 02:50

    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
        if got != want {
            t.Errorf("s.Display() = %q, want %q", got, want)
    解决 无用
    打赏 举报

相关推荐 更多相似问题