Sphere
Log in Join
☆ 3

Testing a CLI that writes to stdout without making a mess in the repo

I am writing a small Go CLI and want integration tests that capture stdout. Right now I shell out from the test, redirect to a temp file, and compare strings, which works but feels clumsy. Is there a standard pattern for injecting an io.Writer into cobra commands so tests stay in-process?

⚑ Report

3 replies

☆ 3
H Hana ·2026-10-31#1

Yes: give your command a field for the output writer, default it to os.Stdout in the constructor, and call cmd.SetOut(out) in tests. Cobra already has SetOut and SetErr on the root command.

⚑ Report
☆ 0
D Dmitri ·2026-11-07#2

I had no idea SetOut existed. That removes most of my helper code.

⚑ Report
☆ 0
R Ravi ·2026-11-08#3

One gotcha: some third-party commands write directly to os.Stdout instead of using the command writer. If you see output leaking into the test log, that is usually why.

⚑ Report
Log in to reply.