0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

GolangのTest入門(Step2:複数ケースのテストケース実行)

Posted at

## はじめに
前回の続きです。今回は1つの関数で複数のテストケースを実行するプログラムを書きたいと思います。

実装

product/product.go
package product

func Add(a, b int) int {
	return a + b
}
test/sample/sample_test.go
package sample

import (
	"fmt"
	"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,
		},
		{
			name: "1+1(失敗)",
			args: args{1, 1},
			expected: 3,
		},
	}

	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 {
				fmt.Println("テスト失敗", tt.name)
				t.Errorf("実行値と期待値が異なります。実行値: %v, 期待値: %v", actual, tt.expected)
			}else {
				fmt.Println("テスト成功", tt.name)
			}
		})
	}
}

実行結果

実行結果
~/go/src/go_test$ go test -v ~/go/src/go_test/test/sample
=== RUN   TestAdd
=== RUN   TestAdd/1+1(成功)
テスト成功 1+1(成功)
=== RUN   TestAdd/1+1(失敗)
テスト失敗 1+1(失敗)
    sample_test.go:36: 実行値と期待値が異なります。実行値: 2, 期待値: 3
--- FAIL: TestAdd (0.00s)
    --- PASS: TestAdd/1+1(成功) (0.00s)
    --- FAIL: TestAdd/1+1(失敗) (0.00s)
FAIL
FAIL    github.com/kouji0705/go-test/test/sample        0.433s
FAIL

NextStep

今回は複数ケースのテストケース実行をしました。次回はMockを利用したテストケースの実装方法を紹介したいと思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?