Golangでテストコードを書く

d yoshikawa
Sep 2, 2018 · 2 min read
  • Go 1.10.2
  • OSX HighSierra

標準パッケージのtestingとサードパーティのstretchr/testifyを使う。

以下の内容でhello_test.goを作成。

package main

import (
"testing"
"github.com/stretchr/testify/assert"
)

func TestHello(t *testing.T) {
assert.Equal(t, true, true)
}

要点は、

  • ファイル名の末尾を _test.go にする。
  • 関数名は Test で始める。
  • テスト関数にtesting.T のポインタ型の引数をとる
  • testingにはassertがないのでtestify/assertをインポートして用いる

実行するには、

go test -run ""
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade