gpt4 book ai didi

unit-testing - mock 去。有简单的方法吗?

转载 作者:行者123 更新时间:2023-11-28 21:04:15 25 4
gpt4 key购买 nike

我来自 python,我一直在寻找一种在 go 中编写 yests 的方法。我在 SO 上遇到过一些事情,但对于一直需要的东西来说,它们似乎都非常繁琐和冗长。

我现在在手机上打字,如果需要的话稍后会添加代码...但是例如...

假设我有一个在中间某处调用 smtp.Send 的函数。如何轻松测试此功能?

假设我有另一个点击一些外部 api(需要模拟)然后获取响应并调用类似 ioutil.Readall() 的东西......我怎么才能通过这个测试函数并模拟对 api 的调用,然后在调用 Readall 时传递一些伪造的响应数据?

最佳答案

您可以使用界面来完成。例如,假设您有一个名为 Mailer 的接口(interface):

type Mailer interface {
Send() error
}

现在您可以将 Mailer 对象嵌入到调用 Send 方法的函数中。

type Processor struct {
Mailer
}

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

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

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

p := &Processor{
Mailer: mockMailer,
}

p.Process()

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

关于unit-testing - mock 去。有简单的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42388439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com