計算機科学のブログ

多国通貨(The Money Example) 明白な実装(Degenerate Objects)

テスト駆動開発 (Kent Beck(著)、和田 卓人(翻訳)、オーム社)の第Ⅰ部(多国通貨(The Money Example))、第2章(明白な実装(Degenerate Objects))をJavaではなくGo言語で取り組んでみる。

コード

money_test.go

package money

import "testing"

func TestMultiplication(t *testing.T) {
	five := NewDollar(5)
	// five.Times(2)
	// got := five.Amount
	// want := 10
	// if got != want {
	// 	t.Errorf("five.Amount got %v, want %v", got, want)
	// }
	// five.Times(3)
	// got = five.Amount
	// want = 15
	// if got != want {
	// 	t.Errorf("five.Amount got %v, want %v", got, want)
	// }
	tests := []struct {
		m, want int
	}{
		{2, 10},
		{3, 15},
	}
	for _, test := range tests {
		got := five.Times(test.m).Amount
		want := test.want
		if got != want {
			t.Errorf("five.Times(%v) got %v, want %v", test.m, got, want)
		}
	}
}

money.go

package money

// Dollar ...
type Dollar struct {
	Amount int
}

// NewDollar ...
func NewDollar(amount int) Dollar {
	return Dollar{Amount: amount}
}

// Times ...
func (d Dollar) Times(m int) Dollar {
	return NewDollar(d.Amount * m)
}

入出力結果(Terminal, Zsh)

% go test
--- FAIL: TestMultiplication (0.00s)
    money_test.go:17: five.Amount got 30, want 15
FAIL
exit status 1
FAIL	money	0.413s
% go test
PASS
ok  	money	0.282s
%