A Go example function demonstrates how to use code and can verify standard output when its name follows the Example<FunctionName> convention and its body declares expected output. section 2.1.2 section 2.6
Use the convention as follows:
- Place tests for unexposed functions in the same package as the source file. section 2.1.2
- Name the function with Example<FunctionName>; for an unexposed main function, Example_main follows the demonstrated convention. section 2.1.2
- Call the tested function, then add an // Output: comment followed by the expected standard-output lines. section 2.1.2
- Run go test to execute eligible examples; without an Output comment, an example is compiled and documented but not executed during tests. section 2.1.2
Checking printed output
A test function can call main and declare Hello world as the expected output. Running go test reports PASS when the generated output matches. section 2.1.2 section 2.6
Listing 2.2 main_internal_test.go: Testing the printed output
package main
func Example_main() {
main() #1
// Output: #2
// Hello world
}
View the complete Example_main listing, including the call to main and the Output comment. section 2.1.2
> go test PASS ok learngo-pockets/hello 0.008s
View the terminal result showing go test passing for the package. section 2.1.2
