diff options
author | Jasper Ras <jaspert.ras@gmail.com> | 2025-05-20 07:19:33 +0200 |
---|---|---|
committer | Jasper Ras <jaspert.ras@gmail.com> | 2025-05-20 07:19:33 +0200 |
commit | a61d928b279c5c508aca3bfc7cb14d810c3d75de (patch) | |
tree | 6df664d4b58f1266e2782252547ed35e3c960b34 /Redirecting output during testing.md | |
parent | d4bd3ad4a869c87fcfa4f83b42555a6c8e1bc746 (diff) |
vault backup: 2025-05-20 07:19:33
Diffstat (limited to 'Redirecting output during testing.md')
-rw-r--r-- | Redirecting output during testing.md | 43 |
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 |