Home > Net >  Golang: mock struct functions for a test
Golang: mock struct functions for a test

Time:11-22

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?

CodePudding user response:

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

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

func emitGauge(s Gauger, i float64) {
    s.Gauge("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
}
  •  Tags:  
  • go
  • Related