Golang:为测试模拟结构体函数

huangapple go评论64阅读模式
英文:

Golang: mock struct functions for a test

问题

这是我要翻译的内容:

go版本:1.19x

这是我想要测试的函数(statsd是"github.com/DataDog/datadog-go/v5/statsd"外部库)

s, err := statsd.New(StatsdHost)

emitGauge(s, 10.0)

// 需要测试下面的函数
func emitGauge(s *statsd.Client, i float64) {

    // 调用statsd的Gauge函数
    // s.Gauge("name", i, "", 1)

}

我希望我的测试通过一个模拟对象来替代statsd.Client,并断言传递给s.Gauge的值是否正确。

我尝试过以下代码:

type StubStatsd struct{}

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

但是我得到了Cannot use 'statsdStub' (type StubStatsd) as the type *statsd.Client的错误。

如何正确测试这种类型的函数?

英文:

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?

答案1

得分: 2

你需要修改你的函数来接受一个接口。

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

func emitGauge(s Gauger, i float64) {
    s.Gauge("name", i, "", 1)
}

然后你可以像之前的模拟一样进行操作。

type StubStatsd struct{}

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

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
}

huangapple
  • 本文由 发表于 2022年11月22日 02:49:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/74523586.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定