【发布时间】:2012-10-01 15:49:49
【问题描述】:
我正在尝试针对单个模块功能编写单元测试。该模块与其他一些模块协作,因此我想模拟这些模块以隔离我的测试系统。下面是一些简化的伪代码:
local moduleFoo={}
local moduleBaz= require("moduleBaz")
moduleFoo.doSomething = function (arg)
if moduleBaz.bar.neatMethod(arg) then
--does something interesting
end
end
return moduleFoo
这是moduleBaz的代码
local moduleBaz={}
moduleBaz.bar= {}
moduleBaz.bar.neatMethod=function(arg)
--does something neat
end
return moduleBaz
我正在尝试使用 package.preload 函数在我的测试运行之前注入一个 moduleBaz 的模拟实例,但它似乎不起作用(即在测试中使用了 moduleBaz 的真实实例,而不是我的模拟)
这是一些伪测试代码:
package.loaded.moduleBaz= nil
local moduleBaz = {}
moduleBaz.bar = {}
moduleBaz.bar.neatMethod= function(guid) return true end
package.preload['moduleBaz'] = function ()
return moduleBaz
end
local foo= require("moduleFoo")
foo.doSomething('asdasdasda')--real moduleBaz is called, not my mock!
任何想法我做错了什么?我对 Lua 很陌生,对语言中如何处理范围完全不满意!
【问题讨论】:
-
您是否也在使用
package.loaded.moduleFoo= nil以确保您没有使用旧版本的moduleFoo? -
我确实尝试过。它似乎没有任何效果,因为 package.preload 从未被调用过。