How to test io.writer in golang?

Recently, I hope to write unit test for golang. The function is as follows.

func (s *containerStats) Display(w io.Writer) error { fmt.Fprintf(w, "%s %s\n", "hello", "world") return nil } 

So, how can I check the result of "func Display" - this is "hello world"?

+6
source share
1 answer

You can simply transfer your own io.Writer and check what is written in it, corresponds to what you expect. bytes.Buffer is a good choice for such an io.Writer , as 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) } } 
+12
source

Source: https://habr.com/ru/post/984824/


All Articles