A lightweight test helper package
0

Configure Feed

Select the types of activity you want to include in your feed.

Ensure we have a README section for output capture (#19)

authored by

Tom Fleet and committed by
GitHub
(Jan 18, 2024, 2:47 PM UTC) bcb75eb6 933aa62a

+27
+27
README.md
··· 184 184 } 185 185 ``` 186 186 187 + ### Capturing Stdout and Stderr 188 + 189 + We've all been there, trying to test a function that prints but doesn't accept an `io.Writer` as a destination 🙄. 190 + 191 + That's where `test.CaptureOutput` comes in! 192 + 193 + ```go 194 + func TestOutput(t *testing.T) { 195 + // Function that prints to stdout and stderr, but imagine this is defined somewhere else 196 + // maybe a 3rd party library that you don't control, it just prints and you can't tell it where 197 + fn := func() error { 198 + fmt.Fprintln(os.Stdout, "hello stdout") 199 + fmt.Fprintln(os.Stderr, "hello stderr") 200 + 201 + return nil 202 + } 203 + 204 + // CaptureOutput to the rescue! 205 + stdout, stderr := test.CaptureOutput(t, fn) 206 + 207 + test.Equal(t, stdout, "hello stdout\n") 208 + test.Equal(t, stderr, "hello stderr\n") 209 + } 210 + ``` 211 + 212 + 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. 213 + 187 214 ### Credits 188 215 189 216 This package was created with [copier] and the [FollowTheProcess/go_copier] project template.