LoginSignup
35
12

More than 5 years have passed since last update.

The Go Playground で Test & Example がしやすくなった

Last updated at Posted at 2018-03-22

以前までは、The Go Playground で実行できる Go Command は go run のみだったので、テストを書きたい場合

previous_test_description
package main

import "testing"

func Hello(name string) string {
    return "Hello, Emacs!"
}

func TestHello(t *testing.T) {
    if Hello("Vim") != "Hello, Vim!" {
        t.Error("Use Vim!!!")
    }
}

func matchString(a, b string) (bool, error) {
    return true, nil
}

func main() {
    testSuite := []testing.InternalTest {
        {Name: "TestHello", F: TestHello},
    }
    testing.Main(matchString, testSuite, nil, nil)
}

といった感じにまわりくどく書く必要がありました。

しかし、先日マージされたコミットにより気軽にテストができるようになりました。

テストのやり方は単純で、

  1. ソースコードに main 関数を含めない
  2. 普段テスト関数を書くように func TestXxx(*testing.T) を用意する

の2点を守ることです。

current_test_description
package main

import "testing"

func Hello(name string) string {
    return "Hello, Emacs!"
}

func TestHello(t *testing.T) {
    if Hello("Vim") != "Hello, Vim!" {
        t.Error("Use Vim!!!")
    }
}

あとは実行ボタンを押せば、特別な設定なしに自動でテストモードへと切り替わり、テストが実行されます。
なお 2018/3/23 現在、BenchExample には対応していないので、実装されるのを気長に待つか Issue を書いちゃいましょう!

【追記】2018/4/11

3月の終わりにマージされたコミット により Example にも対応しました。

  1. ソースコードに main 関数を含めない
  2. ソースコードに func TestXxx(*testing.T) 関数を含めない
  3. testing パッケージをインポートしない
  4. 普段 Example を書くように func ExampleXxx() 関数を用意する

の4点を守ることで Example を使うことができます。

35
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
35
12