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.

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

local_mock(..., .env = topenv(), .local_envir = parent.frame())

## Arguments

... named parameters redefine mocked functions, unnamed parameters will be evaluated after mocking the functions the environment in which to patch the functions, defaults to the top-level environment. A character is interpreted as package name. Environment in which to add exit hander. For expert use only.

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

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

## References

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

## Examples

add_one <- function(x) x + 1
with_mock(
add_one = function(x) x - 1,
expect_equal(
with_mock(
add_one = function(x) x - 1,
),
1
# local_mock() -------------------------------
plus <- function(x, y) x + y
test_that("plus(1, 1) == 2", {
expect_equal(plus(1, 1), 2)
})

test_that("plus(1, 1) == 3", {
local_mock(plus = function(x, y) 3)
expect_equal(plus(1, 1), 3)
})#> Error: Test failed: 'plus(1, 1) == 3'
#> Backtrace:
#>  1. testthat::local_mock(plus = function(x, y) 3)
#>  2. testthat:::extract_mocks(list(...), .env = .env)
#>  3. base::lapply(...)
#>  4. testthat:::FUN(X[[i]], ...)