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.
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 therest.http
library. This is what I did in my test:This approach should work for any exported function. For example, to replace function
foo
from librarybar
.Changing global functions or variables can be achieved by overwriting
_G
, for instance, this will change the global function or variablefoo
:Busted supports to automatically restore the environment. Search for "insulate" in the documentation.