![goコマンド『test』](https://mitikusa-engineer.com/wp-content/uploads/2022/07/Go-1024x538.png)
Goで自作したパッケージを自動テストする方法をまとめました。
サンプル
サンプルコードを用意
下記ソースコードをテストしてみます。
.
├── animals
│ ├── cat.go
│ └── dog.go
├── go.mod
└── main.go
// cat.go
package animals
func CatCry(pattern int) string {
var result string = ""
if pattern == 1 {
result = "にゃーん"
} else if pattern == 2 {
result = "ごろにゃーん"
} else {
result = "キシャー!"
}
return result
}
// dog.go
package animals
func DogCry(pattern int) string {
var result string = ""
if pattern == 1 {
result = "わんわん"
} else if pattern == 2 {
result = "わおーん"
} else {
result = "グルルル..."
}
return result
}
// go.mod
module sample
go 1.18
// main.go
package main
import (
"fmt"
"sample/animals"
)
func main() {
fmt.Println(animals.DogCry(1))
fmt.Println(animals.CatCry(2))
}
テストコードを用意
テスト用ファイルは『_test.go』で終わるファイル名にします。
.
├── animals
│ ├── animals_test.go
│ ├── cat.go
│ └── dog.go
├── go.mod
└── main.go
テスト用ファイルにテストコードを実装します。
関数名『TestXxx』の単位でテストを書いていきます。一般的には『Xxx』の部分がテスト対象の関数名を指すことが多いと思います。
// animals_test.go
package animals
import (
"testing"
)
# CatCry関数のテスト
func TestCatCry(t *testing.T) {
answerList := []string{"キシャー!", "にゃーん", "ごろにゃーん"}
for idx, answer := range answerList {
result := CatCry(idx)
if answer != result {
t.Errorf("実行結果[%s]と期待する結果[%s]が不一致です。", result, answer)
}
}
}
# DogCry関数のテスト
func TestDogCry(t *testing.T) {
answerList := []string{"わんわん", "わおーん", "グルルル..."}
//answerList := []string{"グルルル...", "わんわん", "わおーん"}
for idx, answer := range answerList {
result := DogCry(idx)
if answer != result {
t.Errorf("実行結果[%s]と期待する結果[%s]が不一致です。", result, answer)
}
}
}
テストは下記コマンドで実行します。
go test -v ./animals/
========================================
=== RUN TestCatCry
--- PASS: TestCatCry (0.00s)
=== RUN TestDogCry
animals_test.go:23: 実行結果[グルルル...]と期待する結果[わんわん]が不一致です。
animals_test.go:23: 実行結果[わんわん]と期待する結果[わおーん]が不一致です。
animals_test.go:23: 実行結果[わおーん]と期待する結果[グルルル...]が不一致です。
--- FAIL: TestDogCry (0.00s)
FAIL
FAIL sample/animals 0.003s
FAIL