是否可以模拟从 golang 中的包导入的函数? [英] Is it possible to mock a function imported from a package in golang?

查看:20
本文介绍了是否可以模拟从 golang 中的包导入的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法进行测试,该方法使用从包中导入的函数.

I have the following method to test, which uses a function imported from a package.

import x.y.z

func abc() {
    ...
    v := z.SomeFunc()
    ... 
}

是否可以在 golang 中模拟 SomeFunc()?

Is it possible to mock SomeFunc() in golang?

推荐答案

是的,通过简单的重构.创建一个函数类型的 zSomeFunc 变量,用 z.SomeFunc 初始化,并让你的包调用它而不是 z.SomeFunc():

Yes, with a simple refactoring. Create a zSomeFunc variable of function type, initialized with z.SomeFunc, and have your package call that instead of z.SomeFunc():

var zSomeFunc = z.SomeFunc

func abc() {
    // ...
    v := zSomeFunc()
    // ...
}

在测试中,您可以为 zSomeFunc 分配另一个函数,该函数在测试中定义,并执行测试想要它做的任何事情.

In tests you may assign another function to zSomeFunc, one that is defined in tests, and does whatever the test wants it to.

例如:

func TestAbc(t *testing.T) {
    // Save current function and restore at the end:
    old := zSomeFunc
    defer func() { zSomeFunc = old }()

    zSomeFunc = func() int {
        // This will be called, do whatever you want to,
        // return whatever you want to
        return 1
    }

    // Call the tested function
    abc()

    // Check expected behavior
}

查看相关/可能重复:测试 os.ExitGo 中包含覆盖信息的场景 (coveralls.io/Goveralls)

这篇关于是否可以模拟从 golang 中的包导入的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆