在Go语言中进行模拟测试有简单的方法吗?

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

mocking in go. Is there an easy way?

问题

我来自Python,一直在寻找一种在Go语言中编写测试的方法。我在Stack Overflow上找到了一些方法,但它们似乎都非常繁琐和冗长,而这些方法应该是经常需要的。

我现在正在手机上输入,如果需要的话,稍后会添加代码...但是举个例子...

假设我有一个函数,在中间调用了smtp.Send,我如何轻松地测试这个函数呢?

再假设我有另一个函数,它调用了一些外部API(需要模拟),然后获取响应并调用类似于ioutil.Readall()的函数...我该如何通过测试函数并模拟对API的调用,并在调用Readall时传递一些虚假的响应数据呢?

英文:

I come from python and I have been looking for a way to write yests in go. I have come across a few things on SO but they all seem very cumbersome and verbose for something that shpuld be needed all the time.

I am typing on mobile now, will add code later if needed...but for example...

say i have a function that calls smtp.Send somewhere in the middle. how can I easily test this function?

Say i have another one that hits some outside api (needs mocking) and then takes the response and calls something like ioutil.Readall()...how could i make my way through this test function and mock the call to the api and then pass some fake response data when Readall is called?

答案1

得分: 5

你可以通过使用接口来实现。例如,假设你有一个名为Mailer的接口:

type Mailer interface {
    Send() error
}

现在,你可以将一个Mailer对象嵌入到调用Send方法的函数中:

type Processor struct {
    Mailer
}

func (p *Processor) Process() {
    _ = p.Mailer.Send()
}

现在,在你的测试中,你可以创建一个模拟的Mailer:

type mockMailer struct{}
// 根据你的需求实现mockMailer的Send方法

p := &Processor{
    Mailer: mockMailer{},
}

p.Process()

p.Process调用到Send方法时,它会调用你模拟的Send方法。

英文:

You can do it by using an interface. For example let's say you have an interface called Mailer:

type Mailer interface {
    Send() error
}

Now you can embed a Mailer object into the function that calls the Send method.

type Processor struct {
    Mailer
}

func (p *Processor) Process() {
    _ = p.Mailer.Send()
}

Now in your test you can create a mock Mailer.

type mockMailer struct{}
//implement the Send on the mockMailer as you wish

p := &Processor{
    Mailer: mockMailer,
}

p.Process()

when p.Process reaches the Send method it calls your mocked Send method.

huangapple
  • 本文由 发表于 2017年2月22日 18:05:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/42388439.html
匿名

发表评论

匿名网友

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

确定