lunarmodules / busted

Elegant Lua unit testing.
https://lunarmodules.github.io/busted/
MIT License
1.39k stars 184 forks source link

Mocking global file that is not avaliable #676

Open RicardoMonteiroSimoes opened 2 years ago

RicardoMonteiroSimoes commented 2 years ago

Hello,

I'm currently building up a test suite for our drivers in lua. Right now I have the following problem, that I want to "mock" a global object (class? file?). My test currently requires my main .lua file, and I can succesfully test global variables. Now, that file contains the following codebit:

function CreateMessageParameters()
    return {
        [G_scRoom] = C4:ListGetRoomID(),
        [G_scC4Id] = C4:GetDeviceID(),
        [G_scAddress] = G_scDeviceAddress
    }
end

The C4 is not a library I have access to - so I can't really test it, but thats okay. I would want to make a test like this, in a different file, that has the file from above as required:

it("CreateMessageParameters should call the correct functions", function()
        C4 = { 
            ListGetRoomID = function() return "roomID" end,
            GetDeviceID = function() return "deviceID" end
        }

        stub(C4, "ListGetRoomID")
        stub(C4, "GetDeviceID")

        CreateMessageParameters()
        assert.stub(C4.ListGetRoomID).was.called()
        assert.stub(C4.GetDeviceID).was.called()

Now, of course, this doesn't work because attempt to index global 'C4' (a nil value). Is there a way to mock/stub this?