Unit testing 在围棋中嘲笑。有简单的方法吗?
我来自python,一直在寻找一种用go编写Yest的方法。我在这方面遇到了一些事情,但它们似乎都很麻烦,而且对于一些随时都需要的东西来说冗长 我现在正在手机上打字,如果需要的话,我会在以后添加代码…但例如 < >我有一个函数调用<代码> SMTP。在中间发送某处的< /代码>。如何轻松测试此功能Unit testing 在围棋中嘲笑。有简单的方法吗?,unit-testing,testing,go,mocking,Unit Testing,Testing,Go,Mocking,我来自python,一直在寻找一种用go编写Yest的方法。我在这方面遇到了一些事情,但它们似乎都很麻烦,而且对于一些随时都需要的东西来说冗长 我现在正在手机上打字,如果需要的话,我会在以后添加代码…但例如 < >我有一个函数调用 SMTP。在中间发送某处的< /代码>。如何轻松测试此功能 假设我有另一个命中一些外部api(需要模拟),然后接受响应并调用类似于ioutil.Readall()的东西…调用Readall时,我如何通过这个测试函数模拟对api的调用,然后传递一些虚假的响应数据?您可以
假设我有另一个命中一些外部api(需要模拟),然后接受响应并调用类似于
ioutil.Readall()的东西
…调用Readall
时,我如何通过这个测试函数模拟对api的调用,然后传递一些虚假的响应数据?您可以通过使用接口来实现。例如,假设您有一个名为Mailer的接口:
type Mailer interface {
Send() error
}
现在,您可以将Mailer对象嵌入调用Send
方法的函数中
type Processor struct {
Mailer
}
func (p *Processor) Process() {
_ = p.Mailer.Send()
}
现在在测试中,您可以创建一个模拟邮件程序
type mockMailer struct{}
//implement the Send on the mockMailer as you wish
p := &Processor{
Mailer: mockMailer,
}
p.Process()
当
p.Process
到达Send
方法时,它会调用模拟的Send
方法。您可以使用一个接口来完成。例如,假设您有一个名为Mailer的接口:
type Mailer interface {
Send() error
}
type Processor struct {
Mailer
}
func (p *Processor) Process() {
_ = p.Mailer.Send()
}
现在,您可以将Mailer对象嵌入调用Send
方法的函数中
type Processor struct {
Mailer
}
func (p *Processor) Process() {
_ = p.Mailer.Send()
}
现在在测试中,您可以创建一个模拟邮件程序
type mockMailer struct{}
//implement the Send on the mockMailer as you wish
p := &Processor{
Mailer: mockMailer,
}
p.Process()
当
p.Process
到达Send
方法时,它调用你的mockSend
方法。发布一些cod,否则很难知道你想做什么发布一些cod,否则很难知道你想做什么感谢这个简单的例子……在这种情况下,我想要测试的函数必须将Mailer接口作为输入…正确吗?@deltaskelta也可以,要模拟API调用,您可以使用net/http/httptest感谢这个简单的示例…在这种情况下,我要测试的函数必须将Mailer接口作为输入…正确吗?@deltaskelta也可以,要模拟API调用,您可以使用net/http/httptest
type Processor struct {
Mailer
}
func (p *Processor) Process() {
_ = p.Mailer.Send()
}