How can stdout be captured or suppressed for Go(lang) testing?

os.Stdout which is used by the fmt.Printf and others is just a variable. So you can overwrite it at any time and restore it back when necessary. https://golang.org/pkg/os/#pkg-variables


The output can be suppressed by running the tests with go test .:

$ go help test

Go test runs in two different modes: local directory mode when invoked with no package arguments (for example, 'go test'), and package list mode when invoked with package arguments (for example 'go test math', 'go test ./...', and even 'go test .').

In local directory mode, go test compiles and tests the package sources found in the current directory and then runs the resulting test binary. In this mode, caching (discussed below) is disabled. After the package test finishes, go test prints a summary line showing the test status ('ok' or 'FAIL'), package name, and elapsed time.

In package list mode, go test compiles and tests each of the packages listed on the command line. If a package test passes, go test prints only the final 'ok' summary line. If a package test fails, go test prints the full test output. If invoked with the -bench or -v flag, go test prints the full output even for passing package tests, in order to display the requested benchmark results or verbose logging.


To suppress the output during the test I use the following code. I fixes output as well as logging. After test is done it resets the output streams.

func TestStartStowWrongCommand(t *testing.T) {
 defer quiet()()   
 ...                      
}

func quiet() func() {
 null, _ := os.Open(os.DevNull)
 sout := os.Stdout
 serr := os.Stderr
 os.Stdout = null
 os.Stderr = null
 log.SetOutput(null)
 return func() {
  defer null.Close()
  os.Stdout = sout
  os.Stderr = serr
  log.SetOutput(os.Stderr)
 }
}

Tags:

Go