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

标签 unit-testing testing go mocking

我来自 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/

相关文章:

go - 将 Go 源代码和覆盖率导入 SonarQube

go - bazel 构建给出 "Argument list too long"错误

database - 单元测试 Restful 网络服务

python - Python单元测试在什么情况下运行失败?

spring - 集成测试 : test the Autowired annotation

angularjs - 使用 Jasmine 测试 Angular Controller 对带有 Promise 返回的服务的调用的最佳方法

java - 在 Jetty 测试中重用 ServletContainerInitializer

c - BPF 尾调用未调用

java - 尝试验证静态方法时出现 NotAMockException

unit-testing - 谷歌模拟的期望