如何在Golang中测试io.writer? [英] How to test io.writer in golang?

查看:47
本文介绍了如何在Golang中测试io.writer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我希望为golang编写单元测试.功能如下.

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
}

那么我如何测试"func Display"的结果是"hello world"?

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

推荐答案

您可以简单地传递自己的 io.Writer 并测试写入其中的内容是否符合您的期望.对于此类 io.Writer bytes.Buffer 是一个不错的选择,因为它只是将输出存储在其缓冲区中.

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

这篇关于如何在Golang中测试io.writer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆