加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

单元测试 – 如何在golang中测试io.writer?

发布时间:2020-12-16 19:26:47 所属栏目:大数据 来源:网络整理
导读:最近我希望为golang写一个单元测试.功能如下. func (s *containerStats) Display(w io.Writer) error { fmt.Fprintf(w,"%s %sn","hello","world") return nil} 那么如何测试“func Display”的结果是“hello world”? 您可以简单地传入您自己的io.Writer并
最近我希望为golang写一个单元测试.功能如下.
func (s *containerStats) Display(w io.Writer) error {
    fmt.Fprintf(w,"%s %sn","hello","world")
    return nil
}

那么如何测试“func Display”的结果是“hello world”?

您可以简单地传入您自己的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 worldn"
    if got != want {
        t.Errorf("s.Display() = %q,want %q",got,want)
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读