0
0

More than 1 year has passed since last update.

GolangのTest入門(Step1:テストコード実装、実行)

Posted at

はじめに

Go言語のテスト実装を1から学び直そうと思い、記事にしています。

ディレクトリ

~/go/src/go_test$ tree 
.
├── go.mod
├── product
│   └── product.go
└── test
    └── sample
        └── sample_test.go

4 directories, 3 files

環境作成

①go.mod initの作成

go.mod init
go mod init github.com/kouji0705/sample_test  

②プロダクトコード実装
productディレクトリにコードを記載。
初回なので可能な限りシンプルな実装にしようと、引数の和を算出するコードです。

product/product.go
package product

func Add(a, b int) int {
	return a + b
}

③テストコード実装
プロダクトコードで書いたコードをテストします。

test/sample/sample_test.go
package sample

import (
	"testing"

	pr "github.com/kouji0705/go-test/product"
)

func TestAdd(t *testing.T) {
	type args struct {
		a int
		b int
	}
	tests := []struct {
		name string
		args args
		expected int
	}{
		{
			name: "1+1",
			args: args{1, 1},
			expected: 2,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if actual := pr.Add(tt.args.a, tt.args.b); actual != tt.expected {
				t.Errorf("実行値と期待値が異なります。実行値: %v, 期待値: %v", actual, tt.expected)
			}
		})
	}
}

実行結果

成功時(引数が1,1:期待値:2)
~/go/src/go_test$ go test -v ~/go/src/go_test/test/sample                       
=== RUN   TestAdd
=== RUN   TestAdd/1+1
--- PASS: TestAdd (0.00s)
    --- PASS: TestAdd/1+1 (0.00s)
PASS
ok      github.com/kouji0705/go-test/test/sample        (cached)

→成功時はPASSが出ます。

失敗時(引数が1,1:期待値:3)
~/go/src/go_test$ go test -v ~/go/src/go_test/test/sample
=== RUN   TestAdd
=== RUN   TestAdd/1+1
    sample_test.go:29: 実行値と期待値が異なります。実行値: 2, 期待値: 3
--- FAIL: TestAdd (0.00s)
    --- FAIL: TestAdd/1+1 (0.00s)
FAIL
FAIL    github.com/kouji0705/go-test/test/sample        0.904s
FAIL

→失敗時はFAILが出ます。

NextStep

今回は関数1件で1ケースのテストを実施しました。次回は関数1つで複数件のテストを実装するテストコードを書きたいと思います。

0
0
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
0
0