Injectable Output With io.Writer
Take an io.Writer parameter instead of writing to os.Stdout directly, so the same report code runs against a buffer in tests and stdout in main.
Code
package main
import (
"bytes"
"fmt"
"io"
"os"
"strings"
)
// render 只依赖 io.Writer:main 给 os.Stdout,测试给 bytes.Buffer
func render(w io.Writer, rows []string) error {
for _, row := range rows {
if _, err := fmt.Fprintf(w, "* %s\n", strings.ToUpper(row)); err != nil {
return err
}
}
_, err := fmt.Fprintf(w, "total %d rows\n", len(rows))
return err
}
func main() {
if err := render(os.Stdout, []string{"deploy", "verify"}); err != nil {
panic(err)
}
// 换一个实现无需改动 render:写入内存缓冲即可做断言
var buf bytes.Buffer
if err := render(&buf, []string{"deploy", "verify"}); err != nil {
panic(err)
}
fmt.Println("captured lines:", strings.Count(buf.String(), "\n"))
}The parameter that makes output swappable
render(w io.Writer, rows []string) error touches no global sink: it writes each row through fmt.Fprintf(w, "* %s\n", strings.ToUpper(row)) and a final fmt.Fprintf(w, "total %d rows\n", len(rows)), returning the first write error it meets. main calls it twice against the same data — once with os.Stdout, once with a bytes.Buffer — and the function body cannot tell the difference.
Same renderer, two destinations
* DEPLOY
* VERIFY
total 2 rows
captured lines: 3
The first three lines come from the os.Stdout call (rows upper-cased by strings.ToUpper, then the total). The last line is the buffer call’s payoff: strings.Count(buf.String(), "\n") counts 3 newlines, proving the same render landed in memory where a test can assert on it.
The lines that route the output
if err := render(os.Stdout, []string{"deploy", "verify"}); err != nil {
panic(err)
}
var buf bytes.Buffer
if err := render(&buf, []string{"deploy", "verify"}); err != nil {
Only the argument changes — no re-implementation, no branch inside render — which is the entire testing story of io.Writer injection.
Interactive Tools for This Topic
FAQ
- How does the code signal failure?
- Through `error` values — the snippet checks `err != nil` at 3 sites, and the entry flow turns failures into `panic(err)`.
- What does Injectable Output With io.Writer print when run?
- No setup needed: run the file and look for labeled lines like `captured lines:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.