% Generated by roxygen2: do not edit by hand % Please edit documentation in R/mock-object.R \name{mock} \alias{mock} \alias{mock_args} \alias{mock_calls} \alias{length.mock} \title{Create and query a mocked function.} \usage{ mock(..., cycle = FALSE, envir = parent.frame()) mock_args(m) mock_calls(m) \method{length}{mock}(x) } \arguments{ \item{...}{Values returned upon subsequent calls.} \item{cycle}{Whether to cycle over the return values. If \code{FALSE}, will fail if called too many times.} \item{envir}{Where to evaluate the expressions being returned.} \item{m}{A \code{\link{mock}}ed function.} \item{x}{A \code{\link{mock}}ed function.} } \value{ \code{mock_args()} returns a \code{list} of \code{list}s of argument values. \code{mock_calls()} returns a \code{list} of \code{call}s. \code{length.mock()} returns the number of calls invoked on \code{m}. } \description{ Mock object's primary use is to record calls that are made on the mocked function. } \details{ Optionally values/expressions can be passed via \code{...} for the mock object to return them upon subsequent calls. Expressions are evaluated in environment \code{envir} before being returned. If no value is passed in \code{...} then \code{NULL} is returned. Passing an expression or a function call via \code{...} 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. \code{mock_calls} and \code{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. } \examples{ library(testthat) f <- function(x) summary(x) local({ m <- mock(1) stub(f, 'summary', m) expect_equal(f(iris), 1) expect_called(m, 1) expect_call(m, 1, summary(x)) expect_args(m, 1, iris) }) # multiple return values local({ m <- mock(1, "a", sqrt(3)) stub(f, 'summary', m) expect_equal(f(iris), 1) expect_equal(f(iris), "a") expect_equal(f(iris), 1.73, tolerance = .01) }) # side effects local({ m <- mock(1, 2, stop("error")) stub(f, 'summary', m) expect_equal(f(iris), 1) expect_equal(f(iris), 2) expect_error(f(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)) }