内容纲要
自己的总结
-
spy.on
和spy.new
的区别-
spy.on
和spy.new
本身的参数定义就不同-
spy.on
方法的参数是(target_table, target_key)
,也就是说它是针对table中的某个method进行spy的。spy.on github codeon = function(target_table, target_key) local s = spy.new(target_table[target_key]) target_table[target_key] = s -- store original data s.target_table = target_table s.target_key = target_key return s end
-
spy.new
方法(callback)
的参数就只有一个是function本身。spy.new github codenew = function(callback) callback = callback or function() end if not util.callable(callback) then error("Cannot spy on type '" .. type(callback) .. "', only on functions or callable elements", util.errorlevel()) end local s = setmetatable({ calls = {}, returnvals = {}, callback = callback, target_table = nil, -- these will be set when using 'spy.on' target_key = nil, revert = function(self) if not self.reverted then if self.target_table and self.target_key then self.target_table[self.target_key] = self.callback end self.reverted = true end return self.callback end, clear = function(self) self.calls = {} self.returnvals = {} return self end, called = function(self, times, compare) if times or compare then local compare = compare or function(count, expected) return count == expected end return compare(#self.calls, times), #self.calls end return (#self.calls > 0), #self.calls end, called_with = function(self, args) local last_arglist = nil if #self.calls > 0 then last_arglist = self.calls[#self.calls].vals end local matching_arglists = util.matchargs(self.calls, args) if matching_arglists ~= nil then return true, matching_arglists.vals end return false, last_arglist end, returned_with = function(self, args) local last_returnvallist = nil if #self.returnvals > 0 then last_returnvallist = self.returnvals[#self.returnvals].vals end local matching_returnvallists = util.matchargs(self.returnvals, args) if matching_returnvallists ~= nil then return true, matching_returnvallists.vals end return false, last_returnvallist end }, spy_mt) assert:add_spy(s) -- register with the current state return s end,
-
spy.on
和spy.new
的返回值不同spy.new
的返回值是一个table,里面包含了revert、clear、called_with、returned_with等增强的方法,并还设置了__call
元方法spy.on
的返回值是在spy.new
返回的table基础上增加target_table
和target_key
这两个字段,他们的值就是上面说的方法的参数(target_table, target_key)
spy.on
和spy.new
的行为不同spy.on
比spy.new
增加了对table里面target_key对应的value值替换为spy.new的结果的行为。code
综上所述,
spy.on
和spy.new
针对的使用对象是不同的,一个是针对function另一个是针对table,从实现上来说,spy.on
只是在spy.new
的基础上增加了对target_table
的target_key
对应的value
进行替换而已。关于这两者之间的关系看一下源码就清清楚楚了。 -
-
mock
和spy.on
、stub
的关系mock(greet) 相当于 spy.on(t, "greet") -- the original method is called mock(greet, true) 相当于 stub(t, "greet") -- the original method is not called
参考文章
先甩一波英文官方文档: https://lunarmodules.github.io/busted/#spies-mocks-stubs
再甩一波源码:https://github.com/lunarmodules/luassert/blob/master/src/spy.lua#L21
Lua busted测试框架中spy,stub,mock之间的区别