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.

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.

Value

  • mock(): a mock_fun object

  • mock_call(): a call (created by base::match.call())

  • mock_arg(): the object used as specified function argument

  • mock_args(): a list of all function arguments used to create a call to the mock_fun object in question

  • mock_n_called(): a scalar integer

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:

  • mock_call(): retrieves the call captured by base::match.call()

  • mock_arg(): retrieves the value of the argument with name passed as string-valued argument arg

  • mock_args(): retrieves a list of all arguments used for calling the mocked function

  • mock_n_called(): counts the number of times the mocked function was called

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.

Examples

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))
#> [1] "mocked request"

mock_call(mk)
#> curl::curl(url = x)
mock_args(mk)
#> $url
#> [1] "https://eu.httpbin.org/get?foo=123"
#> 
#> $open
#> [1] ""
#> 
#> $handle
#> <curl handle> (empty)
#> 
mock_n_called(mk)
#> [1] 1

mk <- mock({
  url
})

with_mock(`curl::curl` = mk, dl(url))
#> [1] "https://eu.httpbin.org/get?foo=123"

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

with_mock(`curl::curl` = mk, dl(url))
#> [1] "mocked request"