简体   繁体   中英

How to test io.writer in 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
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM