The Go Playground で Test & Example がしやすくなった - Qiita に詳しい。
TestXxx
ポイント
import "testing"
するfunc main()
を書かないfunc TestXxx()
を普通に書く
package main import ( "testing" ) func Hello() string { return "Hello" } func TestHello(t *testing.T) { tests := []struct { name string want string }{ {name: "#1", want: "Hello"}, {name: "#2", want: "Goodbye"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := Hello(); got != tt.want { t.Errorf("Hello() = %v, want %v", got, tt.want) } }) } }
=== RUN TestHello === RUN TestHello/#1 === RUN TestHello/#2 prog.go:22: Hello() = Hello, want Goodbye --- FAIL: TestHello (0.00s) --- PASS: TestHello/#1 (0.00s) --- FAIL: TestHello/#2 (0.00s) FAIL 2 tests failed.
https://play.golang.org/p/0MHXSA7tnOJ
ExampleXxx
ポイント
import "testing"
しないfunc main()
を書かないfunc TestXxx()
を書かないfunc ExampleXxx()
を普通に書く
package main import ( "fmt" ) func ExampleHello() { fmt.Println("Hello") // Output: Hello }
=== RUN ExampleHello --- PASS: ExampleHello (0.00s) PASS All tests passed.