計算機科学のブログ

多国通貨(The Money Example) 不要になったら消す(The Root of All Evil) 重複テストの削除

テスト駆動開発 (Kent Beck(著)、和田 卓人(翻訳)、オーム社)の第Ⅰ部(多国通貨(The Money Example))、第11章(不要になったら消す(The Root of All Evil))をJavaではなくGo言語で取り組んでみる。

コード

money_test.go

package money

import "testing"

func TestMoneyTimes(t *testing.T) {
	five := NewMoneyDollar(5)
	tests := []struct {
		m int
		d Money
	}{
		{2, NewMoneyDollar(10)},
		{3, NewMoneyDollar(15)},
	}
	for _, test := range tests {
		got := five.Times(test.m)
		want := test.d
		if got != want {
			t.Errorf("%v.Times(%v) got %v, want %v", five, test.m, got, want)
		}
	}
}
func TestMoneyCurrency(t *testing.T) {
	tests := []struct {
		c string
		m Money
	}{
		{"USD", NewMoneyDollar(1)},
		{"CHF", NewMoneyFranc(1)},
	}
	for _, test := range tests {
		got := test.m.Currency()
		want := test.c
		if got != want {
			t.Errorf("%v.Currency() got %v, want %v",
				test.m, got, want)
		}
	}
}
func TestMoneyEq(t *testing.T) {
	tests := []struct {
		mx, my Money
		want   bool
	}{
		{NewMoneyDollar(5), NewMoneyDollar(5), true},
		{NewMoneyDollar(5), NewMoneyDollar(6), false},
		{NewMoneyFranc(5), NewMoneyDollar(5), false},
	}
	for _, test := range tests {
		got := test.mx.Eq(test.my)
		want := test.want
		if got != want {
			t.Errorf("%v.Eq(%v) got %v, want %v",
				test.mx, test.my, got, want)
		}
	}
}

money.go

package money

import "fmt"

// Money ...
type Money struct {
	amount   int
	currency string
}

func (mx Money) String() string {
	return fmt.Sprintf("%v %v", mx.amount, mx.currency)
}

// NewMoney ...
func NewMoney(amount int, currency string) Money {
	return Money{amount, currency}
}

// Currency ...
func (mx Money) Currency() string {
	return mx.currency
}

// Eq ...
func (mx Money) Eq(my Money) bool {
	return mx.amount == my.amount && mx.currency == my.currency
}

// Times ...
func (mx Money) Times(m int) Money {
	return NewMoney(mx.amount*m, mx.currency)
}

// NewMoneyDollar ...
func NewMoneyDollar(amount int) Money {
	return NewMoney(amount, "USD")
}

// NewMoneyFranc ...
func NewMoneyFranc(amount int) Money {
	return NewMoney(amount, "CHF")
}

入出力結果(Terminal, Zsh)

% go test
PASS
ok  	money	0.446s
% go test -v
=== RUN   TestMoneyTimes
--- PASS: TestMoneyTimes (0.00s)
=== RUN   TestMoneyCurrency
--- PASS: TestMoneyCurrency (0.00s)
=== RUN   TestMoneyEq
--- PASS: TestMoneyEq (0.00s)
PASS
ok  	money	0.067s
%

実装のコードもそのテスト用のコードもかなりスッキリしたコードになった。