テスト駆動開発のパターン(Patterns for Test-Driven Development) グリーンバーのパターン(Green Bar Patterns)三角測量、明白な実装、一から多へ
テスト駆動開発 (Kent Beck(著)、和田 卓人(翻訳)、オーム社)の第Ⅲ部(テスト駆動開発のパターン(Patterns for Tejst-Driven Development))、第28章(グリーンバーのパターン(Green Bar Patterns))をJava、PythonではなくGo言語で取り組んでみる。
コード
sample_test.go
package sample
import "testing"
func TestMyDateYesterday(t *testing.T) {
got := newMyDate("28.2.02")
want := newMyDate("1.3.02").yesterday()
if got != want {
t.Errorf("got %v, want %v", got, want)
}
}
func TestPlus(t *testing.T) {
// got := plus(3, 1)
// want := 4
tests := []struct {
augend, addend, want int
}{
{3, 1, 4},
{3, 4, 7},
}
for _, test := range tests {
got := plus(test.augend, test.addend)
want := test.want
if got != want {
t.Errorf("plus(%v, %v) got %v, want %v",
test.augend, test.addend, got, want)
}
}
}
func TestSum(t *testing.T) {
// got := sum(5)
// want := 5
// if got != want {
// t.Errorf("sum(5) got %v, want %v", got, want)
// }
// got := sum(5, []int{5})
got := sum([]int{5, 7})
want := 12
if got != want {
t.Errorf("sum({5, 7}) got %v, want %v", got, want)
}
}
sample.go
package sample
type myDate struct{}
func newMyDate(s string) myDate {
return myDate{}
}
func (md myDate) yesterday() myDate {
// return myDate{}
// return newMyDate(newMyDate("1.3.02").days().sub(1))
return newMyDate(md.days().sub(1))
}
func (md myDate) days() myDate {
return myDate{}
}
func (md myDate) sub(n int) string {
return "28.2.02"
}
func plus(augend, addend int) int {
// return 4
return augend + addend
}
func sum(ns []int) int {
t := 0
for _, n := range ns {
t += n
}
return t
}
入出力結果(Terminal, Zsh)
% go test
PASS
ok _/.../sample 0.115s
% go test
PASS
ok _/.../sample 0.224s
% go test
PASS
ok _/.../sample 0.295s
% go test
PASS
ok _/.../sample 0.215s
% go test
PASS
ok _/.../sample 0.280s
% go test
PASS
ok _/.../sample 0.293s
% go test
--- FAIL: TestPlus (0.00s)
sample_test.go:26: plus(3, 4) got 4, want 7
FAIL
exit status 1
FAIL _/.../sample 0.280s
% go test
PASS
ok _/.../sample 0.223s
% go test
PASS
ok _/.../sample 0.283s
% go test
PASS
ok _/.../sample 0.280s
% go test
PASS
ok _/.../sample 0.068s
% go test
PASS
ok _/.../sample 0.238s
% go test
--- FAIL: TestSum (0.00s)
sample_test.go:31: sum({5, 7}) got 12, want 5
FAIL
exit status 1
FAIL _/.../sample 0.251s
% go test
PASS
ok _/.../sample 0.232s
% go test -v
=== RUN TestMyDateYesterday
--- PASS: TestMyDateYesterday (0.00s)
=== RUN TestPlus
--- PASS: TestPlus (0.00s)
=== RUN TestSum
--- PASS: TestSum (0.00s)
PASS
ok _/.../sample 0.121s
%