helpers: Mocking helper functions

Description Usage Arguments Details Value Examples

Description

Calls to mock-objects either constructed using mock() or returned by local_mock() can keep track of how they were called and functions mock_call(), mock_arg/s() and mock_n_called() can be used to retrieve related information.

Usage

1
2
3
4
5
6
7
8
9
mock(expr, env = parent.frame())

mock_call(x, call_no = mock_n_called(x))

mock_args(x, call_no = mock_n_called(x))

mock_arg(x, arg, call_no = mock_n_called(x))

mock_n_called(x)

Arguments

expr

Expression to be used as body of the function to be mocked.

env

Environment used as ancestor to the mock function environment.

x

Object of class mock_fun to be queried for call and argument information.

call_no

The call number of interest (in case the function was called multiple times).

arg

String-valued argument name to be retrieved.

Details

A mocking function can be created either from a single object to be used as return value or from an expression which is used as function body. In both cases, the function signature is inferred from the mock-target. Furthermore, closures constructed by mock() are able to keep track of call objects and arguments passed to their respective targets. The following utility functions are available to query this information:

Calls to mock objects are indexed chronologically and both mock_call() and mock_args() provide an argument call_no which can be used to specify which call is of interest, with the default being the most recent (or last) one.

Value

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
url <- "https://eu.httpbin.org/get?foo=123"

mk <- mock("mocked request")
dl <- function(x) curl::curl(x)

with_mock(`curl::curl` = mk, dl(url))

mock_call(mk)
mock_args(mk)
mock_n_called(mk)

mk <- mock({
  url
})

with_mock(`curl::curl` = mk, dl(url))

my_return_val <- "mocked request"
mk <- mock(my_return_val)

with_mock(`curl::curl` = mk, dl(url))

mockthat documentation built on April 23, 2021, 9:07 a.m.