はじめに
あらゆるプログラミング言語でunitテストという作業は必要だが、今回はそのgo言語版について説明する。
今回はgoのデフォルトの testing
を使い、ライブラリのテストを行うものとする。
ディレクトリ構成
1 2 3 4 5 6 |
$ tree . ├── library │ ├── Ave.go # ライブラリ │ └── Ave_test.go # ライブラリのテストプログラム └── main.go # 呼び出し元 |
テスト対象
library/Ave.go は以下の通り
1 2 3 4 5 6 7 8 9 |
package library func Average(s []int) int { total := 0 for _, i := range s { total += i } return int(total / len(s)) } |
受け取ったスライスを元に、平均を計算し、
平均値を返す
テストプログラム
テストプログラムは
import "testing"
を行い、functionは
func TestAverage(t *testing.T)
という名前で作成する必要がある。
1 2 3 4 5 6 7 8 9 10 |
package library import "testing" func TestAverage(t *testing.T) { v := Average([]int{1, 2, 3, 4, 5}) if v != 3 { t.Error("Expected 3, got", v) } } |
テストプログラムを実施する
テスト実施コマンドはこちら
go test ./...
現在のディレクトリで全てのテストプログラムを実施するという意味。
テスト結果(成功時のパターン)
1 2 3 |
$ go test ./... ? github.com/GitSumito/go-sample [no test files] # testがありません ok github.com/GitSumito/go-sample/library 0.009s |
libraryのテストが完了した
詳細を確認する際は -v
オプションを実施する
1 2 3 4 5 6 |
$ go test ./... -v ? github.com/GitSumito/go-sample [no test files] === RUN TestAverage --- PASS: TestAverage (0.00s) PASS ok github.com/GitSumito/go-sample/library 0.008s |
テスト結果(失敗時のパターン)
テストコードをあえて失敗するよう修正する
1 2 3 4 5 6 7 8 9 10 |
package library import "testing" func TestAverage(t *testing.T) { v := Average([]int{1, 2, 3, 4, 5, 6, 7, 8, 9}) if v != 3 { t.Error("Expected 3, got", v) } } |
再度テストを実行
1 2 3 4 5 6 7 |
$ go test ./... -v ? github.com/GitSumito/go-sample [no test files] === RUN TestAverage --- FAIL: TestAverage (0.00s) Ave_test.go:8: Expected 3, got 5 FAIL FAIL github.com/GitSumito/go-sample/library 0.008s |
テストをskipさせる
Skipを使うことによりスキップさせることが可能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package library import "testing" var Debug bool = true func TestAverage(t *testing.T) { if Debug { t.Skip("Skip Reason") } v := Average([]int{1, 2, 3, 4, 5, 6, 7, 8, 9}) if v != 3 { t.Error("Expected 3, got", v) } } |
結果
1 2 3 4 5 6 7 |
$ go test ./... -v ? github.com/GitSumito/go-sample [no test files] === RUN TestAverage --- SKIP: TestAverage (0.00s) Ave_test.go:10: Skip Reason PASS ok github.com/GitSumito/go-sample/library 0.009s |
参考情報
本記事は、udemyの講座で得た情報をメモとしてまとめました。非常に濃厚な講義ですので、以下の講座を強くお勧めします。
https://www.udemy.com/go-fintech/