多国通貨(The Money Example) 歩幅の調整(Times We're Livin' In) 異なる通過間での比較
テスト駆動開発 (Kent Beck(著)、和田 卓人(翻訳)、オーム社)の第Ⅰ部(多国通貨(The Money Example))、第9章(歩幅の調整(Times We’re Livin’ In))をJavaではなくGo言語で取り組んでみる。
コード
money_test.go
package money
import "testing"
func TestDollarTimes(t *testing.T) {
five := NewDollar(5)
tests := []struct {
m int
want Dollar
}{
{2, NewDollar(10)},
{3, NewDollar(15)},
}
for _, test := range tests {
got := five.Times(test.m)
want := test.want
if !got.Eq(want) {
t.Errorf("%v.Times(%v) got %v, want %v", five, test.m, got, want)
}
}
}
func TestDollarEq(t *testing.T) {
five := NewDollar(5)
tests := []struct {
d Eqer
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)
}
}
}
func TestFrancTimes(t *testing.T) {
five := NewFranc(5)
tests := []struct {
m int
want Franc
}{
{2, NewFranc(10)},
{3, NewFranc(15)},
}
for _, test := range tests {
got := five.Times(test.m)
want := test.want
if !got.Eq(want) {
t.Errorf("%v.Eq(%v) got %v, want %v",
five, test.m, got, want)
}
}
}
func TestFrancEq(t *testing.T) {
five := NewFranc(5)
tests := []struct {
d Eqer
want bool
}{
{NewFranc(5), true},
{NewFranc(6), false},
{NewDollar(5), 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
// Money ...
type Money struct {
amount int
currency string
}
// Currency ...
func (m Money) Currency() string {
return m.currency
}
// Eqer ...
type Eqer interface {
Eq(Eqer) bool
}
// Dollar ...
type Dollar struct {
Money
}
// NewDollar ...
func NewDollar(amount int) Dollar {
return Dollar{Money{amount: amount, currency: "USD"}}
}
// Times ...
func (d Dollar) Times(m int) Dollar {
return NewDollar(d.amount * m)
}
// Eq ...
func (d Dollar) Eq(y Eqer) bool {
dy, ok := y.(Dollar)
if ok {
return d.amount == dy.amount
}
return false
}
// Franc ...
type Franc struct {
Money
}
// NewFranc ...
func NewFranc(amount int) Franc {
return Franc{Money{amount: amount, currency: "CHF"}}
}
// Times ...
func (f Franc) Times(m int) Franc {
return NewFranc(f.amount * m)
}
// Eq ...
func (f Franc) Eq(y Eqer) bool {
fy, ok := y.(Franc)
if ok {
return f.amount == fy.amount
}
return false
}
入出力結果(Terminal, Zsh)
% go test
PASS
ok money 0.400s
% go test
PASS
ok money 0.278s
%