local_mock | R Documentation |
local_mock()
temporarily substitutes implementations of package functions.
This is useful for testing code that relies on functions that are
slow, have unintended side effects or access resources that may not be
available when testing.
with_mock()
substitutes, runs code locally, and restores in one go.
local_mock(
...,
.parent = parent.frame(),
.env = get_mock_env(.parent),
.defer_env = parent.frame()
)
with_mock(..., .parent = parent.frame(), .env = get_mock_env(.parent))
... |
|
.parent |
|
.env |
|
.defer_env |
|
This works by adding a shadow environment as a parent of the environment
in which the expressions are evaluated. Everything happens at the R level,
but only functions in your own package can be mocked.
Otherwise, the implementation is modeled after the original version in the
testthat
package, which is now deprecated.
local_mock()
returns NULL
, invisibly.
with_mock()
returns the result of the last unnamed argument.
Visibility is preserved.
Suraj Gupta (2012): How R Searches And Finds Stuff
some_func <- function() stop("oops")
some_other_func <- function() some_func()
my_env <- environment()
tester_func <- function() {
# The default for .env works well most of the time,
# unfortunately not in examples
local_mock(some_func = function() 42, .env = my_env)
some_other_func()
}
try(some_other_func())
tester_func()
tester_func_with <- function() {
with_mock(
some_func = function() 42,
.env = my_env,
{
some_other_func()
}
)
}
tester_func_with()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.