unit-testing - 是否可以模拟从 golang 中的包导入的函数?

标签 unit-testing testing go mocking

我有以下方法来测试,它使用从包中导入的函数。

import x.y.z

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

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

最佳答案

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

var zSomeFunc = z.SomeFunc

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

在测试中,您可以为 zSomeFunc 分配另一个函数,该函数在测试中定义,并执行测试所需的任何操作。

例如:

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
}

查看相关/可能的重复项: Testing os.Exit scenarios in Go with coverage information (coveralls.io/Goveralls)

关于unit-testing - 是否可以模拟从 golang 中的包导入的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42952191/

相关文章:

java - 使用 CouchBase-Lite 移动设备进行单元测试,无需 Android 应用程序上下文

html - 我如何点击 Behat 中的跨度?

go - 比较文本文件的列

go - 如何将数据从默认端口路由到另一个[4001]

django - 如何针对测试数据库运行 Selenium 测试?

java - JUnit 中的 PowerMock

python - 执行 Django 单元测试时如何禁用第三方 API?

ruby-on-rails - Bundle exec rake 测试没有产生结果

testing - Android Alpha 和 Beta 测试的区别/限制/规则是什么?

json - MongoDB 使用 bson.Raw 从查询中返回整个 JSON