Add a mock.func() helper for mocking functions

develop
lethosor 2021-04-10 01:22:03 -04:00
parent f44442e5e9
commit 757736728d
No known key found for this signature in database
GPG Key ID: 76A269552F4F58C1
2 changed files with 54 additions and 1 deletions

@ -1,6 +1,5 @@
local mock = mkmodule('test_util.mock')
--[[
Usage:
patch(table, key, value, callback)
@ -49,4 +48,22 @@ function mock.patch(...)
)
end
function mock.func(return_value)
local f = {
return_value = return_value,
call_count = 0,
call_args = {},
}
setmetatable(f, {
__call = function(self, ...)
self.call_count = self.call_count + 1
table.insert(self.call_args, {...})
return self.return_value
end,
})
return f
end
return mock

@ -98,3 +98,39 @@ function test.patch_callback_return_value()
expect.eq(a, 3)
expect.eq(b, 4)
end
function test.func_call_count()
local f = mock.func()
expect.eq(f.call_count, 0)
f()
expect.eq(f.call_count, 1)
f()
expect.eq(f.call_count, 2)
end
function test.func_call_args()
local f = mock.func()
expect.eq(#f.call_args, 0)
f()
f(7)
expect.eq(#f.call_args, 2)
expect.eq(#f.call_args[1], 0)
expect.eq(#f.call_args[2], 1)
expect.eq(f.call_args[2][1], 7)
end
function test.func_call_args_nil()
local f = mock.func()
f(nil)
f(2, nil, 4)
expect.table_eq(f.call_args[1], {nil})
expect.table_eq(f.call_args[2], {2, nil, 4})
expect.eq(#f.call_args[2], 3)
end
function test.func_call_return_value()
local f = mock.func(7)
expect.eq(f(), 7)
f.return_value = 9
expect.eq(f(), 9)
end