Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 在围棋中嘲笑。有简单的方法吗?_Unit Testing_Testing_Go_Mocking - Fatal编程技术网

Unit testing 在围棋中嘲笑。有简单的方法吗?

Unit testing 在围棋中嘲笑。有简单的方法吗?,unit-testing,testing,go,mocking,Unit Testing,Testing,Go,Mocking,我来自python,一直在寻找一种用go编写Yest的方法。我在这方面遇到了一些事情,但它们似乎都很麻烦,而且对于一些随时都需要的东西来说冗长 我现在正在手机上打字,如果需要的话,我会在以后添加代码…但例如 < >我有一个函数调用 SMTP。在中间发送某处的< /代码>。如何轻松测试此功能 假设我有另一个命中一些外部api(需要模拟),然后接受响应并调用类似于ioutil.Readall()的东西…调用Readall时,我如何通过这个测试函数模拟对api的调用,然后传递一些虚假的响应数据?您可以

我来自python,一直在寻找一种用go编写Yest的方法。我在这方面遇到了一些事情,但它们似乎都很麻烦,而且对于一些随时都需要的东西来说冗长

我现在正在手机上打字,如果需要的话,我会在以后添加代码…但例如

< >我有一个函数调用<代码> SMTP。在中间发送某处的< /代码>。如何轻松测试此功能


假设我有另一个命中一些外部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
方法时,它调用你的mock
Send
方法。

发布一些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()
}