計算機科学のブログ

多国通貨(The Money Example) 原則をあえて破るとき(Franc-ly Speaking)

テスト駆動開発 (Kent Beck(著)、和田 卓人(翻訳)、オーム社)の第Ⅰ部(多国通貨(The Money Example))、第5章(原則をあえて破るとき(Franc-ly Speaking))をJavaではなくGo言語で取り組んでみる。

コード

money_test.go

package money

import "testing"

func TestDollarTimes(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 TestDollarEq(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)
		}
	}
}

func TestFrancTimes(t *testing.T) {
	five := NewFrac(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)
		}
	}
}

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
}

// Frac ...
type Frac struct {
	amount int
}

// NewFrac ...
func NewFrac(amount int) Frac {
	return Frac{amount: amount}
}

// Times ...
func (d Frac) Times(m int) Frac {
	return NewFrac(d.amount * m)
}

// Eq ...
func (d Frac) Eq(c Frac) bool {
	return d.amount == c.amount
}

入出力結果(Terminal, Zsh)

% go test
PASS
ok  	money	0.427s
% go test -v
=== RUN   TestDollarTimes
--- PASS: TestDollarTimes (0.00s)
=== RUN   TestDollarEq
--- PASS: TestDollarEq (0.00s)
=== RUN   TestFrancTimes
--- PASS: TestFrancTimes (0.00s)
PASS
ok  	money	0.074s
%