我可以使用嵌套接口模拟出库代码吗?

时间:2019-09-19 14:39:22

标签: unit-testing go testing interface

我正在尝试在Go代码的测试中模拟第3方库。但是我无法汇编我所采用的方法。有什么方法可以完成这项工作,或者如果我想模拟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

2 个答案:

答案 0 :(得分:1)

将您的依赖项包装在嵌入依赖类型的结构中:

// answer wrap your dependency
type Ta1 struct {
  T1
}
func (Ta1) M1() I2 {
    return Ta2{}
}
type Ta2 struct {
   T2
}

然后它将起作用:

func main() {
    var i1 I1
    i1 = Ta1{}
    i1.M1().M2()
    i1 = Mock1{}
    i1.M1().M2()
}

尝试https://play.golang.org/p/aHr78dY_c9a

答案 1 :(得分:-2)

您不能在Go中模拟结构。仅接口。