多国通貨(The Money Example) 三角測量(Equality for All)
テスト駆動開発 (Kent Beck(著)、和田 卓人(翻訳)、オーム社)の第Ⅰ部(多国通貨(The Money Example))、第3章(三角測量(Equality for All))をJavaではなくGo言語で取り組んでみる。
コード
money_test.go
package money
import "testing"
func TestMultiplication(t *testing.T) {
five := NewDollar(5)
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)
}
}
}
func TestEq(t *testing.T) {
five := NewDollar(5)
tests := []struct {
d Dollar
want bool
}{
{NewDollar(5), true},
{NewDollar(6), false},
}
for _, test := range tests {
got := five.Eq(test.d)
if got != test.want {
t.Errorf("%v.Eq(%v) got %v, want %v",
five, test.d, got, test.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)
}
// Eq ...
func (d Dollar) Eq(c Dollar) bool {
return d.amount == c.amount
}
入出力結果(Terminal, Zsh)
% go test
--- FAIL: TestEq (0.00s)
money_test.go:34: {5}.Eq({6}) got true, want false
FAIL
exit status 1
FAIL money 0.484s
% go test
PASS
ok money 0.229s
% go test
# money [money.test]
./money_test.go:14:28: five.Times(test.m).Amount undefined (type Dollar has no field or method Amount, but does have amount)
FAIL money [build failed]
% go test
PASS
ok money 0.292s
%