13.12 ドキュメントに出力するExampleをコードに記述する

Goではドキュメントに出力するExampleを xxx_test.go内に記載できます。実装したExampleはテスト実行時に動作検証されるので、Exampleが古くて使えないといったケースを防止できます。

Exampleは命名によって出力されるGoDocドキュメントの位置を制御できます。以下のようなソースコードを想定します。

func F() {
	fmt.Println("example_f")
}

type T struct{}

func (t T) M() {
	fmt.Println("example_m")
}

func (t T) String() string {
	return "example_t"
}

表13-1: 命名と制御位置の関係表

命名

位置

補足

ExampleF

関数 F()

x

ExampleT

struct T

y

ExampleT_M

struct T のメソッド M()

y

実際にExampleを実装します。 Exampleは標準出力の期待値を //output: ${expected} と記述することでテストします。

func ExampleF() {
	F()
	// output: example_f
}

func ExampleT() {
	t := T{}
	fmt.Println(t)
	// output: example_t
}

func ExampleT_M() {
	t := T{}
	t.M()
	// output: example_m
}

GoDocの出力は次の画像のようになります。

Exampleを用いたテストについては下記の記事も参考にしてください。 ...