0
0

はじめに

Goでテストコードを書いてみました。

足し算と引き算をする関数

package math

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

func Sub(a, b int) int {
	return a - b
}

テストコード

1つずつの条件でも書けるし、テーブルドリブンテストで複数条件を構造体に定義して、ループで回すことでテストを分かりやすく書くことができる。

package math_test

import (
	"testing"

	"example/math"
)

func TestAdd(t *testing.T) {
	want := 3
	if got := Add(1, 2); got != 3 {
		t.Errorf("want %d but got %d", want, got)
	}
}

func TestSub(t *testing.T) {
	// テーブルドリブンテスト
	tests := []struct {
		name string
		a    int
		b    int
		want int
	}{
		{name: "1-2", a: 1, b: 2, want: -1},
		{name: "2-1", a: 2, b: 1, want: 1},
		{name: "3-3", a: 3, b: 3, want: 0},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := Sub(tt.a, tt.b); got != tt.want {
				t.Errorf("want %d but got %d", tt.want, got)
			}
		})
	}
}

参考

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