Debian Codegraph @

man/mock.Rd

raw
1 % Generated by roxygen2: do not edit by hand
2 % Please edit documentation in R/mock-object.R
3 \name{mock}
4 \alias{mock}
5 \alias{mock_args}
6 \alias{mock_calls}
7 \alias{length.mock}
8 \title{Create and query a mocked function.}
9 \usage{
10 mock(..., cycle = FALSE, envir = parent.frame())
11
12 mock_args(m)
13
14 mock_calls(m)
15
16 \method{length}{mock}(x)
17 }
18 \arguments{
19 \item{...}{Values returned upon subsequent calls.}
20
21 \item{cycle}{Whether to cycle over the return values. If \code{FALSE},
22 will fail if called too many times.}
23
24 \item{envir}{Where to evaluate the expressions being returned.}
25
26 \item{m}{A \code{\link{mock}}ed function.}
27
28 \item{x}{A \code{\link{mock}}ed function.}
29 }
30 \value{
31
32
33 \code{mock_args()} returns a \code{list} of \code{list}s
34 of argument values.
35
36 \code{mock_calls()} returns a \code{list} of \code{call}s.
37
38 \code{length.mock()} returns the number of calls invoked on \code{m}.
39 }
40 \description{
41 Mock object's primary use is to record calls that are made on the
42 mocked function.
43 }
44 \details{
45 Optionally values/expressions can be passed via \code{...} for the
46 mock object to return them upon subsequent calls. Expressions are
47 evaluated in environment \code{envir} before being returned. If no
48 value is passed in \code{...} then \code{NULL} is returned.
49
50 Passing an expression or a function call via \code{...} is also a
51 way to implement side effects: keep track of the state of code
52 under testing, throw an exception when a condition is met, etc.
53
54 \code{mock_calls} and \code{mock_args} can be used to access the
55 list of calls made on a mocked function and a respective list of
56 values of arguments passed to each of these calls.
57 }
58 \examples{
59 library(testthat)
60
61 f <- function(x) summary(x)
62 local({
63 m <- mock(1)
64 stub(f, 'summary', m)
65
66 expect_equal(f(iris), 1)
67 expect_called(m, 1)
68 expect_call(m, 1, summary(x))
69 expect_args(m, 1, iris)
70 })
71
72 # multiple return values
73 local({
74 m <- mock(1, "a", sqrt(3))
75 stub(f, 'summary', m)
76
77 expect_equal(f(iris), 1)
78 expect_equal(f(iris), "a")
79 expect_equal(f(iris), 1.73, tolerance = .01)
80 })
81
82 # side effects
83 local({
84 m <- mock(1, 2, stop("error"))
85 stub(f, 'summary', m)
86
87 expect_equal(f(iris), 1)
88 expect_equal(f(iris), 2)
89 expect_error(f(iris), "error")
90 })
91
92 # accessing call expressions
93 m <- mock()
94 m(x = 1)
95 m(y = 2)
96 expect_equal(length(m), 2)
97 calls <- mock_calls(m)
98 expect_equal(calls[[1]], quote(m(x = 1)))
99 expect_equal(calls[[2]], quote(m(y = 2)))
100
101 # accessing values of arguments
102 m <- mock()
103 m(x = 1)
104 m(y = 2)
105 expect_equal(length(m), 2)
106 args <- mock_args(m)
107 expect_equal(args[[1]], list(x = 1))
108 expect_equal(args[[2]], list(y = 2))
109
110 }