Mocking methods in an existing lua file during Busted tests

3.1k Views Asked by At

I'm wanting to write unit tests for an existing lua file using Busted. I want to swap out some of the methods during the test, so that the file runs with the mocked/stubbed methods rather than the real ones (otherwise it will fail). Some of the methods that the file calls are pulled in from other lua-libraries, and I'd like to mock these too.

How can this be achieved?

Any help appreciated, thanks.

1

There are 1 best solutions below

0
On

I don't think you can easily replace local functions, but it is straightforward to replace exported or global functions.

For example, I needed to mock an HTTP call via http:new().request(...) from the rest.http library. This is what I did in my test:

local http = require 'resty.http'
http.new = function()
  return {
    request = function(self, args)
      -- ... some mock implementation
    end
  }
end

This approach should work for any exported function. For example, to replace function foo from library bar.

local bar = require 'bar'
bar.foo = myMockImpl

Changing global functions or variables can be achieved by overwriting _G, for instance, this will change the global function or variable foo:

_G.foo = ...

Busted supports to automatically restore the environment. Search for "insulate" in the documentation.