mock {mockthat} | R Documentation |
Mocking helper functions
Description
Calls to mock-objects either constructed using mock()
or returned by
local_mock()
can keep track of how they were called and functions
mock_call()
, mock_arg/s()
and mock_n_called()
can be used to retrieve
related information.
Usage
mock(expr, env = parent.frame())
mock_call(x, call_no = mock_n_called(x))
mock_args(x, call_no = mock_n_called(x))
mock_arg(x, arg, call_no = mock_n_called(x))
mock_n_called(x)
Arguments
expr |
Expression to be used as body of the function to be mocked. |
env |
Environment used as ancestor to the mock function environment. |
x |
Object of class |
call_no |
The call number of interest (in case the function was called multiple times). |
arg |
String-valued argument name to be retrieved. |
Details
A mocking function can be created either from a single object to be used
as return value or from an expression which is used as function body. In
both cases, the function signature is inferred from the mock-target.
Furthermore, closures constructed by mock()
are able to keep track of
call objects and arguments passed to their respective targets. The
following utility functions are available to query this information:
-
mock_call()
: retrieves the call captured bybase::match.call()
-
mock_arg()
: retrieves the value of the argument with name passed as string-valued argumentarg
-
mock_args()
: retrieves a list of all arguments used for calling the mocked function -
mock_n_called()
: counts the number of times the mocked function was called
Calls to mock objects are indexed chronologically and both mock_call()
and mock_args()
provide an argument call_no
which can be used to specify
which call is of interest, with the default being the most recent (or last)
one.
Value
-
mock()
: amock_fun
object -
mock_call()
: a call (created bybase::match.call()
) -
mock_arg()
: the object used as specified function argument -
mock_args()
: a list of all function arguments used to create a call to themock_fun
object in question -
mock_n_called()
: a scalar integer
Examples
url <- "https://eu.httpbin.org/get?foo=123"
mk <- mock("mocked request")
dl <- function(x) curl::curl(x)
with_mock(`curl::curl` = mk, dl(url))
mock_call(mk)
mock_args(mk)
mock_n_called(mk)
mk <- mock({
url
})
with_mock(`curl::curl` = mk, dl(url))
my_return_val <- "mocked request"
mk <- mock(my_return_val)
with_mock(`curl::curl` = mk, dl(url))