Skip to content

Commit b07fab0

Browse files
committed
Allow errors to be raised when a mocked call occurs. Closes #3.
1 parent 9fb06dd commit b07fab0

File tree

3 files changed

+53
-1
lines changed

3 files changed

+53
-1
lines changed

spec/mach_spec.lua

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,30 @@ describe('The mach library', function()
8181
end)
8282
end)
8383

84+
it('should allow you to specify errors to be raised when a mocked function is called', function()
85+
local f = mach.mock_function('f')
86+
87+
f:should_be_called():
88+
and_will_raise_error('some error message'):
89+
when(function()
90+
should_fail_with('some error message', function()
91+
f()
92+
end)
93+
end)
94+
end)
95+
96+
it('should allow calls to be completed after a call that raises an error', function()
97+
local f = mach.mock_function('f')
98+
99+
f:should_be_called():
100+
and_will_raise_error('some error message'):
101+
and_then(f:should_be_called():and_will_return(4)):
102+
when(function()
103+
pcall(function() f() end)
104+
assert.is.equal(f(), 4)
105+
end)
106+
end)
107+
84108
it('should allow you to check that a function has been called multiple times', function()
85109
local f = mach.mock_function('f')
86110

src/mach/Expectation.lua

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,16 @@ function expectation:and_will_return(...)
2727
return self
2828
end
2929

30+
function expectation:and_will_raise_error(...)
31+
-- if not self._call_specified then
32+
-- error('cannot set return value for an unspecified call', 2)
33+
-- end
34+
35+
self._calls[#self._calls]:set_error(...)
36+
37+
return self
38+
end
39+
3040
function expectation:when(thunk)
3141
if not self._call_specified then
3242
error('incomplete expectation', 2)
@@ -46,7 +56,13 @@ function expectation:when(thunk)
4656
self._calls[i - 1]:fix_order()
4757
end
4858

49-
return table.remove(self._calls, i):get_return_values()
59+
table.remove(self._calls, i)
60+
61+
if call:has_error() then
62+
error(call:get_error())
63+
end
64+
65+
return call:get_return_values()
5066
end
5167
end
5268

src/mach/ExpectedCall.lua

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,18 @@ function expected_call:get_return_values(...)
3737
return table.unpack(self._return)
3838
end
3939

40+
function expected_call:set_error(...)
41+
self._error = table.pack(...)
42+
end
43+
44+
function expected_call:get_error(...)
45+
return table.unpack(self._error)
46+
end
47+
48+
function expected_call:has_error()
49+
return self._error ~= nil
50+
end
51+
4052
function expected_call:fix_order()
4153
self._ordered = true
4254
end

0 commit comments

Comments
 (0)