Golang: mock struct functions for a test

Issue

go version: 1.19x

Here is the function I want to test (statsd is "github.com/DataDog/datadog-go/v5/statsd" external lib)

s, err := statsd.New(StatsdHost)

emitGauge(s, 10.0)

// need to test below function
func emitGauge(s *statsd.Client, i float64) {

    // calls statsd Gauge function
    // s.Gauge("name", i, "", 1)

}

I want my test to pass in a mock object for statsd.Client and assert that correct values were passed in to s.Gauge

I’ve tried

type StubStatsd struct{}

func (s StubStatsd) Gauge(name string, value float64, tags []string, rate float64) error {
    return nil
}

but I’m getting Cannot use 'statsdStub' (type StubStatsd) as the type *statsd.Client

What’s the right way to test this type of function?

Solution

You would need to change your function to accept an interface.

type Guager interface {
    Gauge(name string, value float64, tags []string, rate float64) error
}

func emitGauge(s Guager, i float64) {
    s.Guage("name", i, "", 1)
}

and then you can do what you had for the mock

type StubStatsd struct{}

func (s StubStatsd) Gauge(name string, value float64, tags []string, rate float64) error {
    return nil
}

Answered By – dave

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.