An example test is a Go test function whose output serves as both executable verification and runnable API documentation. It keeps documentation aligned with changing code. section 2.6 section 2.8
Build an example test by following these conventions:
- Place it in an _test.go file, commonly named example_test.go. section 2.6.1
- Name the function with the Example prefix and omit the *testing.T parameter. section 2.6.1
- Print the demonstrated result directly to standard output. section 2.6.1
- Add an Output comment containing the expected output; the test tool compares it with the captured output. section 2.6.1 section 2.6.2
- Use a separate package such as url_test to demonstrate the exported API from a user's perspective. section 2.6.1
ExampleParse
A practical example calls url.Parse with a GitHub URL, handles a possible error with log.Fatal, prints the parsed value, and records the expected URL beneath an Output comment. A mismatch causes the test to fail. section 2.6.1 section 2.6.2
Figure 2.9 The Parse function’s documentation provides an interactive example.
Interactive package documentation exposes the example beside Parse and provides a Run action for trying it. section 2.6
