From bcb75eb6aed32021789b4cbbd72670ee9428c874 Mon Sep 17 00:00:00 2001 From: Tom Fleet Date: Thu, 18 Jan 2024 14:47:05 +0000 Subject: [PATCH] Ensure we have a README section for output capture (#19) --- README.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/README.md b/README.md index 8cc8fee..09d208e 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,33 @@ func TestTableThings(t *testing.T) { } ``` +### Capturing Stdout and Stderr + +We've all been there, trying to test a function that prints but doesn't accept an `io.Writer` as a destination 🙄. + +That's where `test.CaptureOutput` comes in! + +```go +func TestOutput(t *testing.T) { + // Function that prints to stdout and stderr, but imagine this is defined somewhere else + // maybe a 3rd party library that you don't control, it just prints and you can't tell it where + fn := func() error { + fmt.Fprintln(os.Stdout, "hello stdout") + fmt.Fprintln(os.Stderr, "hello stderr") + + return nil + } + + // CaptureOutput to the rescue! + stdout, stderr := test.CaptureOutput(t, fn) + + test.Equal(t, stdout, "hello stdout\n") + test.Equal(t, stderr, "hello stderr\n") +} +``` + +Under the hood `CaptureOutput` temporarily captures both streams, copies the data to a buffer and returns the output back to you, before cleaning everything back up again. + ### Credits This package was created with [copier] and the [FollowTheProcess/go_copier] project template.