Skip to content

Commit a08c0a5

Browse files
committed
Support for out of order calls with andAlso
1 parent 2006e44 commit a08c0a5

File tree

2 files changed

+36
-3
lines changed

2 files changed

+36
-3
lines changed

mock.lua

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,24 @@ function MockExpectation:when(thunk)
8181

8282
local function called(m, name, args)
8383
assert(#self._calls > 0, 'unexpected call')
84-
assert(self._calls[1]:functionMatches(m), 'unexpected function "' .. name .. '" called', 2)
85-
assert(self._calls[1]:argsMatch(args), 'unexpected arguments provided to function "' .. name .. '"')
8684

87-
return table.remove(self._calls, 1):getReturnValues()
85+
local validFunctionFound = false
86+
87+
for i, call in ipairs(self._calls) do
88+
if call:functionMatches(m) then
89+
validFunctionFound = true
90+
91+
if call:argsMatch(args) then
92+
return table.remove(self._calls, i):getReturnValues()
93+
end
94+
end
95+
end
96+
97+
if not validFunctionFound then
98+
error('unexpected function "' .. name .. '" called', 2)
99+
else
100+
error('unexpected arguments provided to function "' .. name .. '"', 2)
101+
end
88102
end
89103

90104
mockHandle(called, thunk)

spec/mock_spec.lua

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,5 +280,24 @@ describe('The mock library', function()
280280
end)
281281
end)
282282

283+
it('should allow calls to happen out of order when andAlso is used', function()
284+
local f1 = mock:mockFunction('f1')
285+
local f2 = mock:mockFunction('f2')
286+
287+
mock(f1):shouldBeCalled():
288+
andAlso(mock(f2):shouldBeCalled()):
289+
when(function()
290+
f1()
291+
f2()
292+
end)
293+
294+
mock(f1):shouldBeCalledWith(1):
295+
andAlso(mock(f1):shouldBeCalledWith(2)):
296+
when(function()
297+
f1(2)
298+
f1(1)
299+
end)
300+
end)
301+
283302
-- ordering
284303
end)

0 commit comments

Comments
 (0)