開発環境
- macOS High Sierra - Apple (OS)
- Emacs (Text Editor)
- Go (プログラミング言語)
Introducing Go: Build Reliable, Scalable Programs (Caleb Doxsey (著)、O'Reilly Media)のChapter 9.(Testing)、Exercises(No. 1866)1.を取り組んでみる。
コード(Emacs)
~/go/src/introducing-go/chapter8/math/math_test.go(GOPATH="~/go")
package math import "testing" type testpair struct { values []float64 average float64 } var tests = []testpair{ {[]float64{}, 0}, {[]float64{1}, 1}, {[]float64{1, 2}, 1.5}, {[]float64{1, 2, 3, 4, 5}, 3}, {[]float64{-1, 1}, 0}, } func TestAverage(t *testing.T) { for _, pair := range tests { v := Average(pair.values) if v != pair.average { t.Error( "For", pair.values, "expected", pair.average, "got", v, ) } } }
~/go/src/introducing-go/chapter8/math/math.go(GOPATH="~/go")
// Package math provides Min and Max functions that find the minimum and maximum // values in a slice of float64s package math func Average(xs []float64) float64 { if len(xs) == 0 { return 0 } total := 0.0 for _, v := range xs { total += v } return total / float64(len(xs)) } // Finds the minimum values in a slice of float64s func Min(xs []float64) float64 { m := xs[0] for _, x := range xs[1:] { if x < m { m = x } } return m } // Finds the maxmum values in a slice of float64s func Max(xs []float64) float64 { m := xs[0] for _, x := range xs[1:] { if x > m { m = x } } return m }
入出力結果(Terminal)
$ go test --- FAIL: TestAverage (0.00s) math_test.go:22: For [] expected 0 got NaN FAIL exit status 1 FAIL introducing-go/chapter8/math 0.005s $ go test PASS ok introducing-go/chapter8/math 0.006s $
0 コメント:
コメントを投稿