フィボナッチ(Fibonacci) 実装、ベタ書き、共通部分、一般化、パラメータ化テスト
テスト駆動開発 (Kent Beck(著)、和田 卓人(翻訳)、オーム社)の付録B(フィボナッチ(Fibonacci))をJavaではなくGo言語で取り組んでみる。
コード
fibonacci_test.go
package fibonacci
import "testing"
func TestFib(t *testing.T) {
tests := []struct {
n, want int
}{
{0, 0},
{1, 1},
{2, 1},
{3, 2},
}
for _, test := range tests {
got := fib(test.n)
if got != test.want {
t.Errorf("fib(%v) got %v, want %v", test.n, got, test.want)
}
}
}
fibonacci.go
package fibonacci
func fib(n int) int {
if n == 0 {
return 0
}
if n == 1 {
return 1
}
return fib(n-1) + fib(n-2)
}
入出力結果(Terminal, Zsh)
% go test
PASS
ok _/.../fibonacci 0.419s
% go test
PASS
ok _/.../fibonacci 0.281s
% go test
--- FAIL: TestFib (0.00s)
fibonacci_test.go:15: fib(1) got 0, want 1
FAIL
exit status 1
FAIL _/.../fibonacci 0.217s
% go test
PASS
ok _/.../fibonacci 0.220s
% go test
PASS
ok _/.../fibonacci 0.220s
% go test
--- FAIL: TestFib (0.00s)
fibonacci_test.go:17: fib(3) got 1, want 2
FAIL
exit status 1
FAIL _/.../fibonacci 0.249s
% go test
PASS
ok _/.../fibonacci 0.225s
% go test
PASS
ok _/.../fibonacci 0.066s
% go test
PASS
ok _/.../fibonacci 0.223s
% go test
PASS
ok _/.../fibonacci 0.222s
% go test
PASS
ok _/.../fibonacci 0.246s
%