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"?
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
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.
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
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.
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With