Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"?

like image 440
wonderflow Avatar asked Apr 08 '15 02:04

wonderflow


People also ask

What is Io writer in Golang?

CODE EXAMPLE An io.Writer is an entity to which you can write a stream of bytes. The standard library contains many Writers, and Writers are accepted as input by many utilities. About Home Algorithms Go How to use the io.Writer interface yourbasic.org/golang Basics How to use a built-in writer (3 examples) Optimize string writes Basics

What is the use of write method in Golang?

The Write method. The io.Writer interface is used by many packages in the Go standard library and it represents the ability to write a byte slice into a stream of data. More generically allows you to write data into something that implements the io.Writer interface.

How to write test cases in Golang?

Golang provides an in-built testing package for writing test cases. So you will not have to depend upon any external libraries for testing your functionalities. To getting started with your first unit test follow these conventions The filename where you write your test function ends with _test.go. eg : filename_test.go

What is Go programming language?

Go, often referred to as Golang, is a popular programming language built by Google. Its design and structure help you write efficient, reliable, and high-performing programs.


1 Answers

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)
    }
}
like image 104
Paul Hankin Avatar answered Sep 18 '22 20:09

Paul Hankin