Go – How to print in a Go test using the “testing” package

gotesting

I'm running a test in Go with a statement to print something (i.e. for debugging of tests) but it's not printing anything.

func TestPrintSomething(t *testing.T) {
    fmt.Println("Say hi")
}

When I run go test on this file, this is the output:

ok      command-line-arguments  0.004s

The only way to really get it to print, as far as I know, is to print it via t.Error(), like so:

func TestPrintSomethingAgain(t *testing.T) {
    t.Error("Say hi")
}

Which outputs this:

Say hi
--- FAIL: TestPrintSomethingAgain (0.00 seconds)
    foo_test.go:35: Say hi
FAIL
FAIL    command-line-arguments  0.003s
gom:  exit status 1

I've Googled and looked through the manual but didn't find anything.

Best Answer

The structs testing.T and testing.B both have a .Log and .Logf method that sound to be what you are looking for. .Log and .Logf are similar to fmt.Print and fmt.Printf respectively.

See more details here: http://golang.org/pkg/testing/#pkg-index

fmt.X print statements do work inside tests, but you will find their output is probably not on screen where you expect to find it and, hence, why you should use the logging methods in testing.

If, as in your case, you want to see the logs for tests that are not failing, you have to provide go test the -v flag (v for verbosity). More details on testing flags can be found here: https://golang.org/cmd/go/#hdr-Testing_flags