mockr (version 0.1)

with_mock: Mock functions in a package.

Description

Executes code after temporarily substituting 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.

Usage

with_mock(..., .parent = parent.frame(), .env = topenv(.parent))

Arguments

...

[any] named arguments redefine mocked functions, unnamed parameters will be evaluated after mocking the functions

.parent

[environment] the environment in which to evaluate the expressions, defaults to parent.frame(). Usually doesn't need to be changed.

.env

[environment] the environment in which to patch the functions, defaults to topenv(). Usually doesn't need to be changed.

Value

The result of the last unnamed parameter, visibility is preserved

Details

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 pacakge, which is now deprecated.

References

Suraj Gupta (2012): How R Searches And Finds Stuff

Examples

Run this code
# NOT RUN {
some_func <- function() stop("oops")
some_other_func <- function() some_func()
tester_func <- function() {
  with_mock(
    some_func = function() 42,
    some_other_func()
  )
}
try(some_other_func())
tester_func()
# }

Run the code above in your browser using DataLab