Idiomatic way to test console output

Hello Gophers,

the programm I’m currently workin on should print it’s results to the console with a function called PrintResults(result *Result). Now I wanted to add a test function for PrintResults(). But what is the best way to confirm, that the output is correctly formatted?

You can assume that the results have been tested before passing them to the print function. Furthermore, I found this thread on Stackoverflow and want to know, if this is the way to go or not.

Thanks for leaving your feedback.

I’d recommend a function that formats and returns a strong, so you can test it more easily. Since it just takes one Result, perhaps it would be well suited as a method Format() or possibly String().

Failing that, you could pass the function an io.Writer, or there are some tools that can help test stdout. But I’d try one of the restructuring options first, if you can.

I totally forgot that String() existed. This should work fine for my needs.

Thanks for your response.

You can also use Testable examples to test the output to the console.

2 Likes

A quick question: What name does the testing function need to have in order to get counted to the testing coverage?

The current testing function:

func TestResultString(t *testing.T) {
	expect := "a very long \n result text with a lot \n of linebreaks"

	// testResult is a gobal var defined in the test file
	if testResult.String() != expect {
		t.Error("The test result wasn't printed correctly.")
	}
}

It seems that TestResultString() isn’t counted as covered when running go test -cover

After revisiting the description of the testing package it gave me the answer:

The naming convention to declare examples for the package, a function F, a type T and method M on type T are:

func Example() { … }
func ExampleF() { … }
func ExampleT() { … }
func ExampleT_M() { … }

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.