登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-18 17:51:34 329浏览 收藏

Golang不知道大家是否熟悉?今天我将给大家介绍《我可以使用嵌套接口模拟库代码吗?》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!

问题内容

我正在尝试在我的 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


解决方案


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

// 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

你无法在 go 中模拟结构。只有接口。

以上就是《我可以使用嵌套接口模拟库代码吗?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>