英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论