I was very pleased to find that it is fully possible to overwrite existing functions in Lua. It even applies to those built-in functions that can feel as though they are part of the language. I guess that they are actually functions that are defined in the global scope.
Here's a quick example:
> a = 1
> sp = print
> print = function () a = 2 end
> print = sp
This allows full stubbing, mocking and spying on functions during testing, albeit with a little work. You simply save the function you want to stub, mock or spy on and write a function to act as a stub, mock or spy. You can make use of Lua's upvalues to be able to count how many times the function was called in a test.
Here's an example of mocking a function in a test using LuaUnit:
function testMocking ()
saveParseLine = t.parseLine
local parseLineCalled = 0
t.parseLine = function (line)
parseLineCalled = parseLineCalled + 1
t.parseLine = saveParseLine