登录
首页 >  Golang >  Go问答

如何测试依赖是否被正确调用

来源:stackoverflow

时间:2024-04-08 17:09:38 225浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《如何测试依赖是否被正确调用》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

在 go 中,我如何测试是否以正确的方式调用了模拟依赖项。

如果我有一个采用依赖接口的结构,则在注入后我希望能够测试原始模拟对象是否已被调用。

在此示例中,我当前的代码看不到结构值已更改。如果我将代码更改为通过引用传递,则会触发错误:

s.simpleinterface.call 未定义(类型 *simpleinterface 是指向接口的指针,而不是接口)

type SimpleInterface interface {
    Call()
}

type Simple struct {
    simpleInterface SimpleInterface
}

func (s Simple) CallInterface() {
    s.simpleInterface.Call()
}

type MockSimple struct {
    hasBeenCalled bool
}

func (ms MockSimple) Call() {
    ms.hasBeenCalled = true
}

func TestMockCalled(t *testing.T) {
    ms := MockSimple{}
    s := Simple{
        simpleInterface: ms,
    }
    s.CallInterface()

    if ms.hasBeenCalled != true {
        t.Error("Interface has not been called")
    }
}

解决方案


我发现三种简单的方法可以解决此问题:

1-更改 call 方法的签名以接收指向 mocksimple 的指针,并在实例化 simple 结构时为其提供模拟的地址:

func (ms *mocksimple) call() {
    ms.hasbeencalled = true
}

func testmockcalled(t *testing.t) {
    ms := mocksimple{}
    s := simple{
        simpleinterface: &ms,
    }
    s.callinterface()

    if ms.hasbeencalled != true {
        t.error("interface has not been called")
    }
}

2-不是最干净的解决方案,但仍然有效。如果你真的不能使用#1,就使用它。在其他地方声明“hasbeencalled”并更改您的 mocksimple 以保存指向它的指针:

type mocksimple struct {
    hasbeencalled *bool
}

func (ms mocksimple) call() {
    *ms.hasbeencalled = true
}

func testmockcalled(t *testing.t) {
    hasbeencalled := false
    ms := mocksimple{&hasbeencalled}
    s := simple{
        simpleinterface: ms,
    }
    s.callinterface()

    if hasbeencalled != true {
        t.error("interface has not been called")
    }
}

3-可能是一个非常糟糕的解决方案:使用全局变量,所以我只会将其用作最后的手段(始终避免全局状态)。将“hasbeencalled”设置为全局并从方法中修改它。

var hasBeenCalled bool

type MockSimple struct{}

func (ms MockSimple) Call() {
    hasBeenCalled = true
}

func TestMockCalled(t *testing.T) {
    ms := MockSimple{}
    s := Simple{
        simpleInterface: ms,
    }
    s.CallInterface()

    if hasBeenCalled != true {
        t.Error("Interface has not been called")
    }
}

干杯!

今天关于《如何测试依赖是否被正确调用》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

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