Saturday 17 September 2016

Learning Lua - Stubbing, Mocking and Spying on Functions in Testing

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
    > sp(a)
    1
    > print = function () a = 2 end
    > print()
    > sp(a)
    2
    > print = sp
    > print(a)
    2


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
            luaunit.assertEquals(line, 'AAPL')
            return 'AAPL' 
        end
        luaunit.assertEquals(funcThatCallsParseLine(data), 0);
        luaunit.assertEquals(parseLineCalled, 1) 
        t.parseLine =  saveParseLine
    end

No comments: