Hello, last week I've started learning Golang. Following the Tour of Go I've implemented a function to calculate square root of a given float64 number.
import "fmt"
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %g\n", float64(e))
}
// Sqrt calculates the square root of a number.
// If given negative number it returns an error.
func Sqrt(x float64) (float64, error) {
if x < 0 {
return 0, ErrNegativeSqrt(x)
} else {
z := float64(x)
for i := 0; i < 100; i++ {
z -= (z*z - x) / (2 * z)
}
return z, nil
}
}
To test if it's working as expected I've wrote this test:
import (
"math"
"testing"
)
func TestSqrt(t *testing.T) {
var tests = map[float64]float64{
3: math.Sqrt(3),
2: math.Sqrt(2),
1: math.Sqrt(1),
0: math.Sqrt(0),
4: math.Sqrt(4),
5: math.Sqrt(5),
-5: 0,
-1: 0,
}
precision := 0.00000001
for key, expectedVal := range tests {
val, _ := Sqrt(key)
if val < expectedVal-precision || val > expectedVal+precision {
t.Error(
"For", key,
"expected", expectedVal,
"got", val,
)
}
}
}
My question is How do I write a test for the Error
method of ErrNegativeSqrt
type which I wrote so that ErrNegativeSqrt
can implement the error
interface?
Thanks in advance. ❤️
PS. This is my first dev.to post! 🙌
PPS. Feel free to checkout my repo
Top comments (2)
If you are doing table driven tests in Go it's better to run each subtest separately with t.Run. Check it here - dev.to/plutov/table-driven-tests-i...
Do a type assertion to check the error matches the type you hope for.