我可以使用嵌套接口模拟出库代码吗? [英] Can I mock out library code with a nested interface?
本文介绍了我可以使用嵌套接口模拟出库代码吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在go代码的测试中模拟第3方库.但是我无法汇编我所采用的方法.有什么方法可以完成这项工作,或者如果我想模拟 T2.M2
的结果,可以采取另一种方法?
程序包主要进口 ("fmt")//我无法控制的库中的两种类型输入T1 struct {}func(T1)M1()T2 {返回T2 {}}输入T2 struct {}func(T2)M2(){fmt.Println("hello world")}//我创建了这些接口以分配T1的实例//转换为I1类型的变量,这样我就可以模拟T2.M2()的行为//问题是无法编译.类型I1接口{M1()I2}类型I2接口{M2()//我想模拟这个方法}//这样我就可以创建一个模拟了输入Mock1 struct {}func(Mock1)M1()I2 {返回Mock2 {}}输入Mock2 struct {}func(Mock2)M2(){fmt.Println("HELLO WORLD")}func main(){var i1 I1i1 = T1 {}i1.M1().M2()i1 = Mock1 {}i1.M1().M2()}
https://play.golang.org/p/sv-Uuuke1dr
解决方案
将依赖项包装在嵌入依赖类型的结构中:
//回答包装您的依赖关系输入Ta1 struct {T1}func(Ta1)M1()I2 {返回Ta2 {}}输入Ta2 struct {T2}
然后它将起作用:
func main(){var i1 I1i1 = Ta1 {}i1.M1().M2()i1 = Mock1 {}i1.M1().M2()}
尝试 https://play.golang.org/p/aHr78dY_c9a >
I am trying to mock a 3rd party library in a test in my go code. But I cannot compile the approach that I have taken. Is there any way to make this work, or another approach I can take if I want to mock the result of T2.M2
?
package main
import (
"fmt"
)
// Two types in a library that I dont have control over
type T1 struct {}
func (T1) M1() T2 {
return T2{}
}
type T2 struct {}
func (T2) M2() {
fmt.Println("hello world")
}
// I created these interfaces in order to assign an instance of T1
// to a variable of type I1 so that I can mock the behavior of T2.M2()
// problem is that this doesn't compile.
type I1 interface {
M1() I2
}
type I2 interface {
M2() // I want to mock this method
}
// Then I would be able to create a mock
type Mock1 struct {}
func (Mock1) M1() I2 {
return Mock2{}
}
type Mock2 struct {}
func (Mock2) M2() {
fmt.Println("HELLO WORLD")
}
func main() {
var i1 I1
i1 = T1{}
i1.M1().M2()
i1 = Mock1{}
i1.M1().M2()
}
https://play.golang.org/p/sv-Uuuke1dr
解决方案
Wrap your dependency in structs embedding dependent types:
// answer wrap your dependency
type Ta1 struct {
T1
}
func (Ta1) M1() I2 {
return Ta2{}
}
type Ta2 struct {
T2
}
Then it will work:
func main() {
var i1 I1
i1 = Ta1{}
i1.M1().M2()
i1 = Mock1{}
i1.M1().M2()
}
Try on https://play.golang.org/p/aHr78dY_c9a
这篇关于我可以使用嵌套接口模拟出库代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文