DEV Community

radlinskii
radlinskii

Posted on

4

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.




AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

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.

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay