DEV Community

radlinskii
radlinskii

Posted on

How to test methods in Go

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
    }
}
Enter fullscreen mode Exit fullscreen mode

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,
            )
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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

GitHub logo radlinskii / go-playground

Repository created to have fun with Golang.

go-playground

Build Status GoDoc Go Report Card gopherbadger-tag-do-not-edit

Repository created to have fun with Golang.




Top comments (2)

Collapse
 
der_gopher profile image
Alex Pliutau

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...

Collapse
 
quii profile image
Chris James

Do a type assertion to check the error matches the type you hope for.