with_mock

0th

Percentile

Mock functions in a package.

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.

Keywords
internal
Usage
with_mock(..., .env = topenv())
Arguments
...

named parameters redefine mocked functions, unnamed parameters will be evaluated after mocking the functions

.env

the environment in which to patch the functions, defaults to the top-level environment. A character is interpreted as package name.

Details

This works by using some C code to temporarily modify the mocked function in place. On exit (regular or error), all functions are restored to their previous state. This is somewhat abusive of R's internals, and is still experimental, so use with care.

Functions in base packages cannot be mocked, but this can be worked around easily by defining a wrapper function.

Value

The result of the last unnamed parameter

References

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

Aliases
  • with_mock
Examples
# NOT RUN {
add_one <- function(x) x + 1
expect_equal(add_one(2), 3)
with_mock(
  add_one = function(x) x - 1,
  expect_equal(add_one(2), 1)
)
square_add_one <- function(x) add_one(x) ^ 2
expect_equal(square_add_one(2), 9)
expect_equal(
  with_mock(
    add_one = function(x) x - 1,
    square_add_one(2)
  ),
  1
)
# }
Documentation reproduced from package testthat, version 2.0.1, License: MIT + file LICENSE

Community examples

Looks like there are no examples yet.