mock: Create and query a mocked function.

mockR Documentation

Create and query a mocked function.

Description

Mock object's primary use is to record calls that are made on the mocked function.

Usage

mock(..., cycle = FALSE, envir = parent.frame())

mock_args(m)

mock_calls(m)

## S3 method for class 'mock'
length(x)

Arguments

...

Values returned upon subsequent calls.

cycle

Whether to cycle over the return values. If FALSE, will fail if called too many times.

envir

Where to evaluate the expressions being returned.

m

A mocked function.

x

A mocked function.

Details

Optionally values/expressions can be passed via ... for the mock object to return them upon subsequent calls. Expressions are evaluated in environment envir before being returned. If no value is passed in ... then NULL is returned.

Passing an expression or a function call via ... is also a way to implement side effects: keep track of the state of code under testing, throw an exception when a condition is met, etc.

mock_calls and mock_args can be used to access the list of calls made on a mocked function and a respective list of values of arguments passed to each of these calls.

Value

mock() returns a mocked function which can be then used with with_mock.

mock_args() returns a list of lists of argument values.

mock_calls() returns a list of calls.

length.mock() returns the number of calls invoked on m.

Examples

library(testthat)

m <- mock(1)
with_mock(summary = m, {
  expect_equal(summary(iris), 1)
  expect_called(m, 1)
  expect_call(m, 1, summary(iris))
  expect_args(m, 1, iris)
})

# multiple return values
m <- mock(1, "a", sqrt(3))
with_mock(summary = m, {
  expect_equal(summary(iris), 1)
  expect_equal(summary(iris), "a")
  expect_equal(summary(iris), 1.73, tolerance = .01)
})

# side effects
m <- mock(1, 2, stop("error"))
with_mock(summary = m, {
  expect_equal(summary(iris), 1)
  expect_equal(summary(iris), 2)
  expect_error(summary(iris), "error")
})

# accessing call expressions
m <- mock()
m(x = 1)
m(y = 2)
expect_equal(length(m), 2)
calls <- mock_calls(m)
expect_equal(calls[[1]], quote(m(x = 1)))
expect_equal(calls[[2]], quote(m(y = 2)))

# accessing values of arguments
m <- mock()
m(x = 1)
m(y = 2)
expect_equal(length(m), 2)
args <- mock_args(m)
expect_equal(args[[1]], list(x = 1))
expect_equal(args[[2]], list(y = 2))



mockery documentation built on Sept. 27, 2023, 1:07 a.m.