douzhun4124 2019-09-19 14:39
浏览 111
已采纳

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

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

</div>
  • 写回答

2条回答 默认 最新

  • dongpao1873 2019-09-19 15:34
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单