0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Goでテストコードを書く

Posted at

書きます

今回はA Tour of Goのフィボナッチにテストを書く

main.go
package main
import "fmt"
func fibonacci() func() int {
	a, b := 1, 0
	return func() int {
		a, b = b, a+b
		return a
	}
}
func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}
$ go run main.go
0
1
1
2
3
5
8
13
21
34

テストを書く

main_test.go
package main
import "testing"
var Debug bool = false
func TestFibonacci(t *testing.T) {
	if Debug {
		t.Skip("skip")
	}
	f := fibonacci()
	if f() != 0 {
		t.Errorf("err")
	}
	if f() != 1 {
		t.Errorf("err")
	}
	if f() != 1 {
		t.Errorf("err")
	}
	if f() != 2 {
		t.Errorf("err")
	}
	if f() != 3 {
		t.Errorf("err")
	}
}

テスト実行

$ go test
PASS
ok  	example/user/hello	0.227s

今回は変数をクロージャのような形で保持して呼び出すたびにカウントアップするような実装になっているのでテストもそれに沿った形で書いています。リファクタリングもできますが挙動を理解しました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?