liveBook · Manning

Example test

As explained in Go by Example

An example test is a Go test function whose output serves both as an executable check and as documentation for an example of using an API.

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.
A screenshot of a computer

AI-generated content may be incorrect.

Interactive package documentation exposes the example beside Parse and provides a Run action for trying it. section 2.6

How Go by Example covers it

How deep it goes
Explains naming, packages, output capture, expected-output comments, execution, and failure reporting without covering advanced test coverage or benchmarking.
Examples
Demonstrates url.Parse through ExampleParse, an Output comment, interactive documentation, and passing or failing go test commands.
What it assumes
Assumes familiarity with Go packages, functions, errors, imports, and standard testing while introducing example-test conventions.
What you can do after
Build it from scratch as a runnable API example that validates printed output and appears in interactive package documentation.
How it connects
Connects Go testing, standard output, package documentation, exported APIs, and black-box testing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go by Example. The section links point to the parts of the book it draws on.