Use examples as tests
Use examples as tests
Go documentation examples are functions named Example or ExampleXxx in _test.go files. With an Output: comment, go test runs the example and compares its standard output with the comment. Without an output comment, an example is compiled but not executed by the test runner. Use examples to demonstrate a small public API contract.
Create the files shown below in a fresh directory, then run go test -count=1 -v ./... there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples.
--- go.mod ---module example.test/lesson
go 1.23
--- calc.go ---package calc
func Double(n int) int { return n * 2 }
--- calc_test.go ---package calc
import "fmt"
func ExampleDouble() { fmt.Println(Double(4)) // Output: // 8}The output comment specifies the expected text. The example has no testing.T parameter; use fmt.Println to show the result. A mismatch fails go test. The function name connects the example to the exported Double symbol.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: ExampleDoubleAllow unordered output when order is irrelevant
--- go.mod ---module example.test/lesson
go 1.23
--- calc.go ---package calc
func Labels() map[string]int { return map[string]int{"a": 1, "b": 2} }
--- calc_test.go ---package calc
import "fmt"
func ExampleLabels() { for k, v := range Labels() { fmt.Println(k, v) } // Unordered output: // a 1 // b 2}Map iteration order is unspecified. Unordered output compares output lines without requiring their sequence; it still checks their content and multiplicity. If order is part of the API, sort keys explicitly and use Output instead. Examples do not replace detailed tests for errors and boundaries.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: ExampleLabelsTry it locally
Implement Join(a,b string) string with a colon separator and write ExampleJoin showing "x:7". Use a fresh module with the same go.mod shown above; run go test -count=1 -v ./...
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Testing fundamentals 07: Use examples as tests
Check the lesson objective before moving on.
What makes a documentation example run as a test?
When should Unordered output be used?