with_mock: Mock functions in a package.

Description Usage Arguments Details Value References Examples

View source: R/with-mock.R

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

1
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.

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.

Value

The result of the last unnamed parameter, visibility is preserved

References

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

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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()

krlmlr/mockr documentation built on June 20, 2017, 2:16 p.m.