testthat (version 1.0.2)

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(..., .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.

Value

  • The result of the last unnamed parameter

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.

Primitives (such as interactive) cannot be mocked, but this can be worked around easily by defining a wrapper function with the same name.

References

Suraj Gupta (2012): http://obeautifulcode.com/R/How-R-Searches-And-Finds-Stuff{How R Searches And Finds Stuff}

Examples

Run this code
with_mock(
  all.equal = function(x, y, ...) TRUE,
  expect_equal(2 * 3, 4),
  .env = "base"
)
with_mock(
  `base::identical` = function(x, y, ...) TRUE,
  `base::all.equal` = function(x, y, ...) TRUE,
  expect_equal(x <- 3 * 3, 6),
  expect_identical(x + 4, 9)
)
expect_equal(3, 5)
expect_identical(3, 5)

Run the code above in your browser using DataCamp Workspace