Skip to content

Commit a2bec9b

Browse files
committed
Added flexible ordering requirements
1 parent a08c0a5 commit a2bec9b

File tree

2 files changed

+36
-4
lines changed

2 files changed

+36
-4
lines changed

mock.lua

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ ExpectedCall = {}
1717
function ExpectedCall:new(f, args)
1818
local o = {
1919
_f = f,
20+
_ordered = false,
2021
_args = args,
2122
_return = {}
2223
}
@@ -49,6 +50,14 @@ function ExpectedCall:getReturnValues(...)
4950
return table.unpack(self._return)
5051
end
5152

53+
function ExpectedCall:fixOrder()
54+
self._ordered = true
55+
end
56+
57+
function ExpectedCall:hasFixedOrder()
58+
return self._ordered
59+
end
60+
5261
MockExpectation = {}
5362

5463
function MockExpectation:new(m)
@@ -92,6 +101,8 @@ function MockExpectation:when(thunk)
92101
return table.remove(self._calls, i):getReturnValues()
93102
end
94103
end
104+
105+
if call:hasFixedOrder() then break end
95106
end
96107

97108
if not validFunctionFound then
@@ -115,7 +126,8 @@ function MockExpectation:after(thunk)
115126
end
116127

117128
function MockExpectation:andThen(other)
118-
-- Need to handle ordering
129+
self._calls[#self._calls]:fixOrder()
130+
119131
for _, call in ipairs(other._calls) do
120132
table.insert(self._calls, call)
121133
end
@@ -124,7 +136,6 @@ function MockExpectation:andThen(other)
124136
end
125137

126138
function MockExpectation:andAlso(other)
127-
-- Need to handle ordering
128139
for _, call in ipairs(other._calls) do
129140
table.insert(self._calls, call)
130141
end

spec/mock_spec.lua

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -287,8 +287,8 @@ describe('The mock library', function()
287287
mock(f1):shouldBeCalled():
288288
andAlso(mock(f2):shouldBeCalled()):
289289
when(function()
290-
f1()
291290
f2()
291+
f1()
292292
end)
293293

294294
mock(f1):shouldBeCalledWith(1):
@@ -299,5 +299,26 @@ describe('The mock library', function()
299299
end)
300300
end)
301301

302-
-- ordering
302+
it('should not allow calls to happen out of order when andThen is used', function()
303+
local f1 = mock:mockFunction('f1')
304+
local f2 = mock:mockFunction('f2')
305+
306+
shouldFailWith('unexpected function "f2" called', function()
307+
mock(f1):shouldBeCalled():
308+
andThen(mock(f2):shouldBeCalled()):
309+
when(function()
310+
f2()
311+
f1()
312+
end)
313+
end)
314+
315+
shouldFailWith('unexpected arguments provided to function "f1"', function()
316+
mock(f1):shouldBeCalledWith(1):
317+
andThen(mock(f2):shouldBeCalled(2)):
318+
when(function()
319+
f1(2)
320+
f1(1)
321+
end)
322+
end)
323+
end)
303324
end)

0 commit comments

Comments
 (0)