我试图在我的 go 代码中的测试中模拟第三方库。但我无法编译我所采取的方法。有什么方法可以使这项工作有效,或者如果我想模拟 的结果,我可以采取另一种方法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
小怪兽爱吃肉
繁华开满天机
相关分类