1Mock::Sub(3) User Contributed Perl Documentation Mock::Sub(3)
2
3
4
6 Mock::Sub - Mock package, object and standard subroutines, with unit
7 testing in mind.
8
10 # see EXAMPLES for a full use case and caveats
11
12 use Mock::Sub;
13
14 # disable warnings about mocking non-existent subs
15
16 use Mock::Sub no_warnings => 1
17
18 # create the parent mock object
19
20 my $mock = Mock::Sub->new;
21
22 # mock some subs...
23
24 my $foo = $mock->mock('Package::foo');
25 my $bar = $mock->mock('Package::bar');
26
27 # wait until a mocked sub is called
28
29 Package::foo();
30
31 # then...
32
33 $foo->name; # name of sub that's mocked
34 $foo->called; # was the sub called?
35 $foo->called_count; # how many times was it called?
36 $foo->called_with; # array of params sent to sub
37
38 # have the mocked sub return something when it's called (list or scalar).
39
40 $foo->return_value(1, 2, {a => 1});
41 my @return = Package::foo;
42
43 # have the mocked sub perform an action
44
45 $foo->side_effect( sub { die "eval catch" if @_; } );
46
47 eval { Package::foo(1); };
48 like ($@, qr/eval catch/, "side_effect worked with params");
49
50 # extract the parameters the sub was called with (if return_value or
51 # side_effect is not used, we will return the parameters that were sent into
52 # the mocked sub (list or scalar context)
53
54 my @args = $foo->called_with;
55
56 # reset the mock object for re-use within the same scope
57
58 $foo->reset;
59
60 # restore original functionality to the sub
61
62 $foo->unmock;
63
64 # re-mock a previously unmock()ed sub
65
66 $foo->remock;
67
68 # check if a sub is mocked
69
70 my $state = $foo->mocked_state;
71
72 # mock out a CORE:: function. Be warned that this *must* be done within
73 # compile stage (BEGIN), and the function can NOT be unmocked prior
74 # to the completion of program execution
75
76 my ($mock, $caller);
77
78 BEGIN {
79 $mock = Mock::Sub->new;
80 $caller = $mock->mock('caller');
81 };
82
83 $caller->return_value(55);
84 caller(); # mocked caller() called
85
87 Easy to use and very lightweight module for mocking out sub calls.
88 Very useful for testing areas of your own modules where getting
89 coverage may be difficult due to nothing to test against, and/or to
90 reduce test run time by eliminating the need to call subs that you
91 really don't want or need to test.
92
94 Here's a full example to get further coverage where it's difficult if
95 not impossible to test certain areas of your code (eg: you have if/else
96 statements, but they don't do anything but call other subs. You don't
97 want to test the subs that are called, nor do you want to add
98 statements to your code).
99
100 Note that if the end subroutine you're testing is NOT Object Oriented
101 (and you're importing them into your module that you're testing), you
102 have to mock them as part of your own namespace (ie. instead of
103 Other::first, you'd mock MyModule::first).
104
105 # module you're testing:
106
107 package MyPackage;
108
109 use Other;
110 use Exporter qw(import);
111 @EXPORT_OK = qw(test);
112
113 my $other = Other->new;
114
115 sub test {
116 my $arg = shift;
117
118 if ($arg == 1){
119 # how do you test this?... there's no return etc.
120 $other->first();
121 }
122 if ($arg == 2){
123 $other->second();
124 }
125 }
126
127 # your test file
128
129 use MyPackage qw(test);
130 use Mock::Sub;
131 use Test::More tests => 2;
132
133 my $mock = Mock::Sub->new;
134
135 my $first = $mock->mock('Other::first');
136 my $second = $mock->mock('Other::second');
137
138 # coverage for first if() in MyPackage::test
139 test(1);
140 is ($first->called, 1, "1st if() statement covered");
141
142 # coverage for second if()
143 test(2);
144 is ($second->called, 1, "2nd if() statement covered");
145
147 "new(%opts)"
148 Instantiates and returns a new "Mock::Sub" object, ready to be used to
149 start creating mocked sub objects.
150
151 Optional options:
152
153 "return_value => $scalar"
154 Set this to have all mocked subs created with this mock object
155 return anything you wish (accepts a single scalar only. See
156 "return_value()" method to return a list and for further
157 information). You can also set it in individual mocks only (see
158 "return_value()" method).
159
160 "side_effect => $cref"
161 Set this in "new()" to have the side effect passed into all child
162 mocks created with this object. See "side_effect()" method.
163
164 "mock('sub', %opts)"
165 Instantiates and returns a new mock object on each call. 'sub' is the
166 name of the subroutine to mock (requires full package name if the sub
167 isn't in "main::").
168
169 The mocked sub will return the parameters sent into the mocked sub if a
170 return value isn't set, or a side effect doesn't return anything, if
171 available. If in scalar context but a list was sent in, we'll return
172 the first parameter in the list. In list context, we simply receive the
173 parameters as they were sent in.
174
175 Optional parameters:
176
177 See "new()" for a description of the parameters. Both the
178 "return_value" and "side_effect" parameters can be set in this method
179 to individualize each mock object, and will override the global
180 configuration if set in "new()".
181
182 There's also "return_value()" and "side_effect()" methods if you want
183 to set, change or remove these values after instantiation of a child
184 sub object.
185
186 mocked_subs
187 Returns a list of all the names of the subs that are currently mocked
188 under the parent mock object.
189
190 mocked_objects
191 Returns a list of all sub objects underneath the parent mock object,
192 regardless if its sub is currently mocked or not.
193
194 mocked_state('Sub::Name')
195 Returns 1 if the sub currently under the parent mock object is mocked
196 or not, and 0 if not. Croaks if there hasn't been a child sub object
197 created with this sub name.
198
200 These methods are for the children mocked sub objects returned from the
201 parent mock object. See "MOCK OBJECT METHODS" for methods related to
202 the parent mock object.
203
204 "unmock"
205 Restores the original functionality back to the sub, and runs "reset()"
206 on the object.
207
208 "remock"
209 Re-mocks the sub within the object after calling "unmock" on it
210 (accepts the side_effect and return_value parameters).
211
212 "called"
213 Returns true (1) if the sub being mocked has been called, and false (0)
214 if not.
215
216 "called_count"
217 Returns the number of times the mocked sub has been called.
218
219 "called_with"
220 Returns an array of the parameters sent to the subroutine. "confess()s"
221 if we're called before the mocked sub has been called.
222
223 "mocked_state"
224 Returns true (1) if the sub the object refers to is currently mocked,
225 and false (0) if not.
226
227 "name"
228 Returns the name of the sub being mocked.
229
230 "side_effect($cref)"
231 Add (or change/delete) a side effect after instantiation.
232
233 Send in a code reference containing an action you'd like the mocked sub
234 to perform.
235
236 The side effect function will receive all parameters sent into the
237 mocked sub.
238
239 You can use both "side_effect()" and "return_value()" params at the
240 same time. "side_effect" will be run first, and then "return_value".
241 Note that if "side_effect"'s last expression evaluates to any value
242 whatsoever (even false), it will return that and "return_value" will be
243 skipped.
244
245 To work around this and have the side_effect run but still get the
246 return_value thereafter, write your cref to evaluate undef as the last
247 thing it does: "sub { ...; undef; }".
248
249 "return_value"
250 Add (or change/delete) the mocked sub's return value after
251 instantiation. Can be a scalar or list. Send in "undef" to remove
252 previously set values.
253
254 "reset"
255 Resets the functional parameters ("return_value", "side_effect"), along
256 with "called()" and "called_count()" back to undef/false. Does not
257 restore the sub back to its original state.
258
260 This module has a backwards parent-child relationship. To use, you
261 create a mock object using "MOCK OBJECT METHODS" "new" and "mock"
262 methods, thereafter, you use the returned mocked sub object "SUB OBJECT
263 METHODS" to perform the work.
264
265 The parent mock object retains certain information and statistics of
266 the child mocked objects (and the subs themselves).
267
268 To mock CORE::GLOBAL functions, you *must* initiate within a "BEGIN"
269 block (see "SYNOPSIS" for details). It is important that if you mock a
270 CORE sub, it can't and won't be returned to its original state until
271 after the entire program process tree exists. Period.
272
273 I didn't make this a "Test::" module (although it started that way)
274 because I can see more uses than placing it into that category.
275
277 Steve Bertrand, "<steveb at cpan.org>"
278
280 Please report any bugs or requests at
281 <https://github.com/stevieb9/mock-sub/issues>
282
284 <https://github.com/stevieb9/mock-sub>
285
287 CPAN Testers: <http://matrix.cpantesters.org/?dist=Mock-Sub>
288
290 You can find documentation for this module with the perldoc command.
291
292 perldoc Mock::Sub
293
295 Python's MagicMock module.
296
298 Copyright 2016 Steve Bertrand.
299
300 This program is free software; you can redistribute it and/or modify it
301 under the terms of either: the GNU General Public License as published
302 by the Free Software Foundation; or the Artistic License.
303
304 See <http://dev.perl.org/licenses/> for more information.
305
306
307
308perl v5.34.0 2022-01-21 Mock::Sub(3)