Borrowing the API from the now-deprecated testthat::with_mock()
, named
arguments passed as ...
are used to define functions to be mocked, where
names specify the target functions and the arguments themselves are used as
replacement functions. Unnamed arguments passed as ...
will be evaluated
in the environment specified as eval_env
using the mocked functions.
Functions to be stubbed should be specified as they would be used in package
core. This means that when a function from a third party package is
imported, prefixing the function name with pkg_name::
will not give the
desired result. Conversely, if the function is not imported, the package
prefix is of course required. On exit of with_mock()
, the mocked functions
are reverted to their original state.
Replacement functions can either be specified as complete functions, or as
either quoted expressions, subsequently used as function body or objects
used as return values. If functions are created from return values or
complete function bodies, they inherit the signatures from the respective
functions they are used to mock, alongside the ability to keep track of
how they are subsequently called. A constructor for such mock-objects is
available as mock()
, which quotes the expression passed as expr
.
If mocking is desirable for multiple separate calls to the function being
tested, local_mock()
is available, which holds onto the mocked state for
the lifetime of the environment passed as local_env
using
withr::defer()
. Unlike with_mock()
, which returns the result of
evaluating the last unnamed argument passed as ...
, local_mock()
(invisibly) returns the functions used for mocking, which if not fully
specified as functions, will be mock-objects described in the previous
paragraph.