Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

with_mock

Mock functions in a package.


Description

[Superseded]

with_mock() and local_mock() are superseded in favour of the more rigorous techniques found in the mockr and mockery packages.

Mocking allows you to temporary replace the implementation of functions within a package, which 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.

This works by using some C code to temporarily modify the mocked function in place. On exit, all functions are restored to their previous state. This is somewhat abusive of R's internals so use with care. In particular, functions in base packages cannot be mocked; to work aroud you'll need to make a wrapper function in your own package..

Usage

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

.env

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

.local_env

Environment in which to add exit hander. For expert use only.

Value

The result of the last unnamed parameter

3rd edition

[Deprecated]

with_mock() and local_mock() are deprecated in the third edition.

References

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

Examples

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
)

# 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)
})

testthat

Unit Testing for R

v3.0.2
MIT + file LICENSE
Authors
Hadley Wickham [aut, cre], RStudio [cph, fnd], R Core team [ctb] (Implementation of utils::recover())
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.