@kyanny's blog

My thoughts, my life. Views/opinions are my own.

Go: The Go Playground で TestXxx と ExampleXxx の書き方

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.

https://play.golang.org/p/nMc_5f8-pgB