【问题标题】:Unit Testing local function in LuaLua中的单元测试本地功能
【发布时间】:2017-06-08 00:32:52
【问题描述】:

所以我使用 Busted 为现有的 Lua 文件创建单元测试,尽可能不更改文件中的代码。该文件导入另一个文件,然后将该文件中的各种方法存储在本地函数中,就像这样。

[examplefile.lua]
local helper = require "helper.lua"
local helper_accept = helper.accept
local helper_reject = helper.reject

foo = new function()
  -- do something which uses helper_accept
  -- do something which uses helper_reject
end

我想在我的测试中监视这些方法,以确保它们在正确的位置被调用。但是,我无法从测试中找到任何方法来做到这一点。 我试过简单地模拟出辅助方法,如下所示:

[exampletest.lua]

local helper = require "helper.lua"
local examplefile = require "examplefile.lua"

-- mock the helper function to simply return true
helper.accept = new function() return true end
spy.on(helper, "accept")
examplefile:foo
assert.spy(helper).was().called()

但这不起作用,因为真实文件使用 helper_accept 和 helper_reject 方法,而不是 helper.accept 和 helper.reject。

这可以在不更改代码的情况下完成吗? 谢谢。

【问题讨论】:

  • 没有。本地文件不会导出,因此您无法覆盖它们。但是你可以覆盖整个 helper.lua 文件,这样当它加载 helper.accepthelper.reject 时,它会使用你的钩子版本的函数。
  • @ktb 这听起来是合乎逻辑的前进方向。你知道任何可以帮助我做到这一点的文档吗?

标签: unit-testing lua local lua-busted


【解决方案1】:

我能想到的最简单的方法是用钩子存根覆盖“帮助器”库。您可以通过修改package.loaded 表来做到这一点。 package.loaded 表存储了对 require "lib" 的初始调用的结果,因此如果再次调用相同的 require,则不需要重新加载模块。如果您在第一次调用 require "lib" 之前在其中放置了一些东西,它将永远不会真正从文件系统加载库。

在您的情况下,您可能希望实际加载库,但要挂钩所有库访问。我会做这样的事情......

local lib = require "lib"

local function hook_func(_, key)
    print('Accessing "lib" attribute '..tostring(key))
    -- other stuff you might want to do in the hook
    return lib[key]
end

package.loaded["lib"] = setmetatable({}, {__index = hook_func})

【讨论】:

  • 可以确认这一切正常。感谢您的所有帮助。
猜你喜欢
  • 2022-10-20
  • 2017-03-03
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多