テスト駆動開発のパターン(Patterns for Test-Driven Development) リファクタリング(Refactoring) データ構造の変更 一から多へ
テスト駆動開発 (Kent Beck(著)、和田 卓人(翻訳)、オーム社)の第Ⅲ部(テスト駆動開発のパターン(Patterns for Tejst-Driven Development))、第31章(リファクタリング(Refactoring))をJava、PythonではなくGo言語で取り組んでみる。
コード
sample_test.go
package sample
import "testing"
func TestSuite(t *testing.T) {
suite := newSuite()
result := newResult()
suite.add(testMethod)
suite.run(result)
got := result.summary()
want := "1 run, 0 failed"
if got != want {
t.Errorf("%v.summary() got '%v', want '%v'", result, got, want)
}
}
sample.go
package sample
import "fmt"
func testMethod() {}
type suite struct {
// f func()
fs []func()
}
func newSuite() *suite {
return &suite{}
}
func (s *suite) add(f func()) {
// s.f = f
s.fs = append(s.fs, f)
}
func (s *suite) run(r *result) {
// r.run++
// s.f()
for _, f := range s.fs {
r.run++
f()
}
r.log = fmt.Sprintf("%v run, %v failed", r.run, r.failed)
}
type result struct {
run, failed int
log string
}
func newResult() *result {
return &result{}
}
func (r *result) summary() string {
return r.log
}
入出力結果(Terminal, Zsh)
% go test
--- FAIL: TestSuite (0.00s)
sample_test.go:13: &{}.summary() got , want 1 run, 0 failed
FAIL
exit status 1
FAIL _/Users/.../sample 0.458s
% go test
--- FAIL: TestSuite (0.00s)
sample_test.go:13: &{0 0 0 run, 0 failed}.summary() got , want 1 run, 0 failed
FAIL
exit status 1
FAIL _/Users/.../sample 0.278s
% go test
--- FAIL: TestSuite (0.00s)
sample_test.go:13: &{0 0 0 run, 0 failed}.summary() got '0 run, 0 failed', want '1 run, 0 failed'
FAIL
exit status 1
FAIL _/Users/.../sample 0.223s
% go test
PASS
ok _/Users/.../sample 0.249s
% go test
Hit
PASS
ok _/Users/.../sample 0.301s
%