微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

最近我希望为golang写一个单元测试.功能如下.
func (s *containerStats) display(w io.Writer) error {
    fmt.Fprintf(w,"%s %s\n","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 world\n"
    if got != want {
        t.Errorf("s.display() = %q,want %q",got,want)
    }
}

原文地址:https://www.jb51.cc/go/186872.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐