1. Writing a good suite of tests is not always easy, but the process of writing
tests often reveals more about a problem then you may at first realize. For example,
with our Average
function what happens if you pass in an empty list ([]float64{})
?
How could we modify the function to return 0
in this case?
If we pass an empty list Average
returns NaN
because we are trying to divide by 0
(the length of the list). We can solve this by checking if the list is empty and returning
0
if so:
func Average(xs []float64) float64 {
if len(xs) == 0 {
return 0
}
total := float64(0)
for _, x := range xs {
total += x
}
return total / float64(len(xs))
}
2. Write a series of tests for the Min
and Max
functions you wrote in the previouse chapter.
package math
import "testing"
type minTestPair struct {
values []float64
min float64
}
type maxTestPair struct {
values []float64
max float64
}
var minTests = []minTestPair {
{ []float64{1, 5}, 1},
{ []float64{6, 2, 5}, 2},
{ []float64{9, 22, 3}, 3},
}
var maxTests = []maxTestPair {
{ []float64{1, 5}, 5},
{ []float64{6, 2, 5}, 6},
{ []float64{9, 22, 3}, 22},
}
func TestMin(t *testing.T) {
for _, pair := range minTests {
v := Min(pair.values)
if v != pair.min {
t.Error(
"For", pair.values,
"expected", pair.min,
"got", v,
)
}
}
}
func TestMax(t *testing.T) {
for _, pair := range maxTests {
v := Max(pair.values)
if v != pair.max {
t.Error(
"For", pair.values,
"expected", pair.max,
"got", v,
)
}
}
}