lunarmodules / luassert

Assertion library for Lua
MIT License
202 stars 76 forks source link

Create spy/stub that replaces an original function with another function? #176

Closed mrrogge closed 3 years ago

mrrogge commented 3 years ago

From the busted docs:

Spies are essentially wrappers around functions that keep track of data about how the function was called, and by default calls the function.

Stubs act similarly to spies, except they do not call the function they replace. This is useful for testing things like data layers.

So spies call the original function, and stubs do not. I'm wondering if there is a way to replace a function with a spy or stub that also calls a new function. For example:

local testModule = {
    testFunction=function() end
}

spy.on(testModule, 'testFunction', function() print('replaced original') end)

For now I'm just monkeypatching the original as a workaround, but it would be nice if I could use the revert() to undo the change at the end of the test.

Edit: reworded my question a little bit

mrrogge commented 3 years ago

Aha, just found out this works:

local testModule = {
    testFunction=function() end
}

stub(testModule, 'testFunction', function() print('replaced original') end)
testModule.testFunction()    --'replaced original'

If I find time I'll do a PR to update the docs with this info. I'll go ahead and close the issue.