計算機科学のブログ

テスト駆動開発のパターン(Patterns for Tejst-Driven Development)

テスト駆動開発 (Kent Beck(著)、和田 卓人(翻訳)、オーム社)の第Ⅲ部(テスト駆動開発のパターン(Patterns for Tejst-Driven Development))、第25章(テスト駆動開発のパターン(Patterns for Tejst-Driven Development))をJavaではなくGo言語で取り組んでみる。

コード

transaction_test.go

package sample

import "testing"

func TestCompleteTransactionIsClosed(t *testing.T) {
	// writer := newServer(defaultPort(), "abc")
	reader := newSocket("localhost", defaultPort())
	got := reader.isClosed()
	want := true
	if got != want {
		t.Errorf("%v.isClosed() got %v, want %v", reader, got, want)
	}
	reply := reader.contents()
	gotContents := reply.contents()
	wantCoontents := "abc"
	if gotContents != wantCoontents {
		t.Errorf("%v.contents() got %v, want %v",
			reply, gotContents, wantCoontents)
	}
}

transaction.go

package sample

type server struct {
}

func newServer(port int, msg string) server {
	return server{}
}

type socket struct {
}

func newSocket(address string, port int) socket {
	return socket{}
}
func (s socket) isClosed() bool {
	return true
}
func (s socket) contents() contents {
	return contents{}
}

type contents struct {
}

func (c contents) contents() string {
	return "abc"
}

func defaultPort() int {
	return 0
}

bank_test.go

package sample

import "testing"

func TestBank(t *testing.T) {
	bank := newBank()
	// bank.addRate("USD", "GBP", STANDARD_RATE)
	// bank.commission(STANDARD_COMMISSION)
	bank.addRate("USD", "GBP", 2)
	bank.commission(0.015)
	got := bank.convert(newNote(100, "USD"), "GBP")
	want := newNote(100/2*(1-0.015), "GBP")
	if got.Ne(want) {
		t.Errorf("bank.convert(newNote(100, USD), GBP) got %v, want %v", got, want)
	}
}

bank.go

package sample

type bank struct {
	from, to string
	rate, c  float64
}

func newBank() bank {
	return bank{}
}
func (b *bank) addRate(from, to string, rate float64) {
	b.from = from
	b.to = to
	b.rate = rate
}
func (b *bank) commission(c float64) {
	b.c = c
}
func (b *bank) convert(n note, s string) note {
	return note{}
}

type note struct{}

func newNote(f float64, s string) note {
	return note{}
}
func (nx note) Eq(ny note) bool {
	return true
}
func (nx note) Ne(ny note) bool {
	return !nx.Eq(ny)
}

入出力結果(Terminal, Zsh)

% go test
--- FAIL: TestCompleteTransactionIsClosed (0.00s)
    transaction_test.go:11: {}.isClosed() got false, want true
    transaction_test.go:17: {}.contents() got , want abc
FAIL
exit status 1
FAIL	_/.../ch25/sample	0.318s
% go test
--- FAIL: TestCompleteTransactionIsClosed (0.00s)
    transaction_test.go:17: {}.contents() got , want abc
FAIL
exit status 1
FAIL	_/.../ch25/sample	0.219s
% go test
PASS
ok  	_/.../ch25/sample	0.221s
% code bank_test.go
% code bank.go
% go test                   
PASS
ok  	_/.../ch25/sample	0.309s
% go test -v
=== RUN   TestBank
--- PASS: TestBank (0.00s)
=== RUN   TestCompleteTransactionIsClosed
--- PASS: TestCompleteTransactionIsClosed (0.00s)
PASS
ok  	_/.../ch25/sample	0.065s
%