summaryrefslogtreecommitdiff
path: root/Redirecting output during testing.md
diff options
context:
space:
mode:
Diffstat (limited to 'Redirecting output during testing.md')
-rw-r--r--Redirecting output during testing.md43
1 files changed, 43 insertions, 0 deletions
diff --git a/Redirecting output during testing.md b/Redirecting output during testing.md
new file mode 100644
index 0000000..f4eda0b
--- /dev/null
+++ b/Redirecting output during testing.md
@@ -0,0 +1,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()
+ }
+}
+``` \ No newline at end of file