計算機科学のブログ

多国通貨(The Money Example) 仮実装(Multi-Currency Money)

テスト駆動開発 (Kent Beck(著)、和田 卓人(翻訳)、オーム社)の第Ⅰ部(多国通貨(The Money Example))、第1章(仮実装(Multi-Currency Money))を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)
	}
}

money.go

package money

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

// NewDollar ...
func NewDollar(amount int) Dollar {

	// return Dollar{Amount: 10}
	// return Dollar{Amount: 5 * 2}
	return Dollar{Amount: amount}
}

// Times ...
func (d *Dollar) Times(m int) {
	// d.Amount = 5 * 2
	// d.Amount = d.Amount * 2
	// d.Amount *= 2
	d.Amount *= m
}

入出力結果(Terminal, Zsh)

% go test
--- FAIL: TestMultiplication (0.00s)
    money_test.go:11: five.Amount got 0, wantr 10
FAIL
exit status 1
FAIL	money	0.069s
% go test
PASS
ok  	money	0.225s
% go test
PASS
ok  	money	0.223s
% go test
PASS
ok  	money	0.283s
% go test
PASS
ok  	money	0.286s
% go test
PASS
ok  	money	0.216s
% go test
PASS
ok  	money	0.220s
% go test
PASS
ok  	money	0.222s
% go test
PASS
ok  	money	0.251s
%