Goでのテスト
Goでのテストには付属のtestingパッケージが使えますが、試しにTestify(https://github.com/stretchrcom/testify)を使ってみました。
インストール。
go get github.com/stretchrcom/testify
テスト対象として以下のようなプログラムがあった場合。
package estimate type Estimater interface { Set(good int, bad int) Good() bool Bad() bool Score() int } type Estimate struct { good, bad int } func (s *Estimate) Set(good int, bad int) { s.good = good s.bad = bad } func (s *Estimate) Good() bool { return (s.good > s.bad) } func (s *Estimate) Bad() bool { return (s.bad > s.good) } func (s *Estimate) Score() int { return s.good - s.bad } type EstimateString struct { value string Estimate }
テスト内容は以下のようになる。
package estimate import ( "github.com/stretchrcom/testify/assert" "testing" ) func TestEstimate(t *testing.T) { e := &Estimate{good: 1, bad: 0} assert.False(t, e.Bad(), "Bad() should be false!") assert.True(t, e.Good(), "Good() should be true!") assert.Equal(t, 1, e.Score(), "they should be equal") } func TestEstimateString(t *testing.T) { e := &EstimateString{ "test", Estimate{good: 0, bad: 0}, } assert.False(t, e.Bad(), "Bad() should be false!") assert.False(t, e.Good(), "Good() should be false!") assert.Equal(t, "test", e.value, "they should be equal") } func TestEstimater(t *testing.T) { var e interface{} = &EstimateString{ "", Estimate{good: 1, bad: 2}, } var e2 Estimater = e.(Estimater) assert.True(t, e2.Bad(), "Bad() should be true!") }
後は普通にテスト実行すれば成否が出力される。
go test
馴染んだ書き方が出来てこっちの方がいいかな。
github.com/stretchrcom/testify/assert 以外にもhttpやmockがあるようです。
- 作者: 古川昇
- 出版社/メーカー: シーアンドアール研究所
- 発売日: 2012/11/21
- メディア: 単行本(ソフトカバー)
- クリック: 7回
- この商品を含むブログ (2件) を見る