unit-testing - go - 如何在测试用例中模拟结构的方法调用
问题描述
这是结构及其方法的示例代码
type A struct {}
func (a *A) perfom(string){
...
...
..
}
然后我想从invoke()
位于包外的函数中调用该方法,示例代码
var s := A{}
func invoke(url string){
out := s.perfom(url)
...
...
}
invoke
我想通过模拟perform
A的方法来编写函数的测试用例。
在java中,我们有mockito、jmock框架来存根方法调用。
有什么办法,我们可以在不引入interfaces
源代码的情况下模拟结构的方法调用吗?
解决方案
要模拟方法调用,您需要模拟您的结构。
使用您提供的代码示例,我建议您制作一个Performer
实现您的Perform
调用的接口。您的真实结构和模拟结构都将实现此接口。
我还建议将您的结构作为参数传递给调用函数,而不是使用全局变量。
这是一个例子:
type Performer interface {
perform()
}
type A struct {
}
func (a *A) perform() {
fmt.Println("real method")
}
type AMock struct {
}
func (a *AMock) perform () {
fmt.Println("mocked method")
}
func caller(p Performer) {
p.perform()
}
在您的测试中,将模拟注入到您的invoke
调用中。在您的真实代码中,将真实结构注入到您的invoke
调用中。
使用像https://godoc.org/github.com/stretchr/testify/mock这样的库,你甚至可以很容易地验证你的方法是用正确的参数调用的,调用了正确的次数,并控制模拟的行为。
推荐阅读
- javascript - 无论我尝试什么,引导模式都不会聚焦
- deep-learning - 使用 Unet 架构的图像去噪
- excel - 如何初始化表单中的组合框?
- ios - 尾随闭包传递给“结果”类型的参数
' 不接受关闭。Google 登录完成检查 - html - 显示:块不适用于图像以消除间隙
- ios - 如何通过 Swift 的 API 将自定义贴纸从我的应用程序共享到电报应用程序?
- derivative - 在 OpenMDAO 的 ExecComp 中,shape_by_conn 是否与 has_diag_partials 兼容?
- authentication - cors 错误预检导致 apollo 客户端和服务器的来源不匹配
- node.js - Mongoose 子文档更新:点符号赋值或 .findByIdAndUpdate()
- python - 使用 FiPy 求解一维球体中的菲克第二扩散定律