@
@
@mgyk2015-04-03 15:15:49
Lua
@mgyk, 2015-04-03 15:15:49

How to use stub/mock in lua (busted)?

function processEvent(e)
  eventId = getEventType(e)
  if eventId == 3 then
    return 3
  else
    return 0
  end
end

I want to override getEventType call
package.path = "../?.lua;" .. package.path
describe("processEvent", function()
  it("EventId==3", function()  
    function getEventType() return 3 end
    chunk = assert(loadfile("templates/sr.lua"))
    chunk()
    assert.are.equal(processEvent('hello'), 3)
  end)
end)

It is not entirely clear how to correctly load code from another file if the code is not wrapped in a module. How can I intercept the getEventType() function call without modifying the source code and return the value I need?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Boris Nagaev, 2015-04-06
@starius

I tried to test something like this using stub:

it("calls getEventType with the event", function()
    function getEventType()
      return 3
    end
    stub(_G, "getEventType")
    processEvent(42)
    assert.stub(getEventType).was.called_with(42)
    getEventType:revert()
  end)

Does not work, although it should, based on the documentation. I wrote to the developers about it.
As a result, I tested everything without spy, mock and stub. In my opinion, if there are not an insane amount of monitored functions, then it is better to keep it simple.
It is not entirely clear how to correctly load code from another file if the code is not wrapped in a module.
Use the dofile function. But it's better to make modules from the tested files and load them using require.
Code note: don't overuse global variables.
UPD . Busted responded that because busted uses a test sandbox, global variables are scoped within the current spec or describe block. They suggested how to still test the processEvent function (assign to _G fields), but this required changing its code. The moral is: don't use global variables.
UPD2 . Advisedeclare global functions in a separate module, which can be connected via require in tests. Then the global variables will get into _G tests and everything will work as expected. Sample code taken from the answer:
-- processEvent.lua
function getEventType(e)
  ...
end

function processEvent(e)
  eventId = getEventType(e)
  if eventId == 3 then
    return 3
  else
    return 0
  end
end

-- process_event_spec.lua
require 'processEvent'

describe("processEvent", function()
  it("calls getEventType with the event", function()
    stub(_G, "getEventType")
    processEvent(42)
    assert.stub(getEventType).was.called_with(42)
    getEventType:revert()
  end)
end)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question