summaryrefslogtreecommitdiff
path: root/Redirecting output during testing.md
blob: f4eda0b32fa1dd3cda918f784737ac3e4af87511 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
---
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()
	}
}
```