--- tags: - golang - testing --- [[Testing Golang programs]] Some functions print or log to stdout/stderr, but during testing we would like to capture this. Here is an example of how to do that: ```echo.go package echo import ( "fmt" "io" "os" "strings" ) var out io.Writer = os.Stdout func echo() { fmt.Fprintln(out, strings.Join(os.Args[1:], " ")) } ``` We define an io.Writer at the package level which is used to write our output to. During tests we can set this to be a buffer, ie: ```echo_test.go package echo import ( "bytes" "testing" ) func BenchmarkEcho(b *testing.B) { out = new(bytes.Buffer) for b.Loop() { echo() } } ```