1Test::MockObject(3) User Contributed Perl Documentation Test::MockObject(3)
2
3
4
6 Test::MockObject - Perl extension for emulating troublesome interfaces
7
9 use Test::MockObject;
10 my $mock = Test::MockObject->new();
11 $mock->set_true( 'somemethod' );
12 ok( $mock->somemethod() );
13
14 $mock->set_true( 'veritas')
15 ->set_false( 'ficta' )
16 ->set_series( 'amicae', 'Sunny', 'Kylie', 'Bella' );
17
19 It's a simple program that doesn't use any other modules, and those are
20 easy to test. More often, testing a program completely means faking up
21 input to another module, trying to coax the right output from something
22 you're not supposed to be testing anyway.
23
24 Testing is a lot easier when you can control the entire environment.
25 With Test::MockObject, you can get a lot closer.
26
27 Test::MockObject allows you to create objects that conform to
28 particular interfaces with very little code. You don't have to
29 reimplement the behavior, just the input and the output.
30
31 IMPORTANT CAVEATS
32 Before you go wild with your testing powers, consider three caveats:
33
34 • It is possible to write highly detailed unit tests that pass even
35 when your integration tests may fail. Testing the pieces
36 individually does not excuse you from testing the whole thing
37 together.
38
39 • In cases where you only need to mock one or two pieces of an
40 existing module, consider Test::MockObject::Extends instead.
41
42 • If the code under testing produces strange errors about type
43 checks, pass the "-debug" flag when using "Test::MockObject" or
44 "Test::MockObject::Extends". This will load both UNIVERSAL::isa and
45 UNIVERSAL::can to perform additional debugging on the incorrect use
46 of both methods from the UNIVERSAL package. (This behavior used to
47 be active by default, but that was, however correct, probably a
48 burden to onerous for the CPAN.)
49
50 EXPORT
51 None.
52
53 METHODS
54 The most important thing a Mock Object can do is to conform
55 sufficiently to an interface. For example, if you're testing something
56 that relies on CGI.pm, you may find it easier to create a mock object
57 that returns controllable results at given times than to fake query
58 string input.
59
60 The Basics
61
62 • "new"
63
64 Creates a new mock object. By default, this is a blessed hash.
65 Pass a reference to bless that reference.
66
67 my $mock_array = Test::MockObject->new( [] );
68 my $mock_scalar = Test::MockObject->new( \( my $scalar ) );
69 my $mock_code = Test::MockObject->new( sub {} );
70 my $mock_glob = Test::MockObject->new( \*GLOB );
71
72 Mocking
73
74 Your mock object is nearly useless if you don't tell it what it's
75 mocking. This is done by installing methods. You control the output
76 of these mocked methods. In addition, any mocked method is tracked.
77 You can tell not only what was called, but which arguments were passed.
78 Please note that you cannot track non-mocked method calls. They will
79 still be allowed, though Test::MockObject will carp() about them. This
80 is considered a feature, though it may be possible to disable this in
81 the future.
82
83 As implied in the example above, it's possible to chain these calls
84 together. Thanks to a suggestion from the fabulous Piers Cawley (CPAN
85 RT #1249), this feature came about in version 0.09. Shorter testing
86 code is nice!
87
88 • "mock(name, coderef [, name2, coderef2, ...])"
89
90 Adds one or more coderefs to the object. This allows code to call
91 the named methods on the object. For example, this code:
92
93 my $mock = Test::MockObject->new();
94 $mock->mock( 'fluorinate',
95 sub { 'impurifying precious bodily fluids' } );
96 print $mock->fluorinate;
97
98 will print a helpful warning message. Please note that methods are
99 only added to a single object at a time and not the class. (There
100 is no small similarity to the Self programming language or the
101 Class::Prototyped module.)
102
103 This method forms the basis for most of Test::MockObject's testing
104 goodness.
105
106 Please Note: this method used to be add(). Due to its ambiguity,
107 it now has a different spelling. For backwards compatibility
108 purposes, add() is available, though version 0.07 deprecated it.
109 It goes to some contortions to try to do what you mean, but I make
110 few guarantees.
111
112 • "fake_module(module name), [ subname =" coderef, ... ]
113
114 Note: See Test::MockModule for an alternate (and better) approach.
115
116 Lies to Perl that it has already loaded a named module. This is
117 handy when providing a mockup of a real module if you'd like to
118 prevent the actual module from interfering with the nice fakery.
119 If you're mocking Regexp::English, say:
120
121 $mock->fake_module( 'Regexp::English' );
122
123 This is both a class and as an object method. Beware that this
124 must take place before the actual module has a chance to load.
125 Either wrap it in a BEGIN block before a use or require or place it
126 before a use_ok() or require_ok() call.
127
128 You can optionally add functions to the mocked module by passing
129 them as name => coderef pairs to fake_module(). This is handy if
130 you want to test an import():
131
132 my $import;
133 $mock->fake_module(
134 'Regexp::English',
135 import => sub { $import = caller }
136 );
137 use_ok( 'Regexp::Esperanto' );
138 is( $import, 'Regexp::Esperanto',
139 'Regexp::Esperanto should use() Regexp::English' );
140
141 If you use fake_module() to mock a module that already exists in
142 memory -- one you've loaded elsewhere perhaps, but do not pass any
143 subroutines to mock, this method will throw an exception. This is
144 because if you call the constructor later on, you probably won't
145 get a mock object back and you'll be confused.
146
147 • "fake_new(module name)"
148
149 Note: see Test::MockObject::Extends for a better alternative to
150 this method.
151
152 Provides a fake constructor for the given module that returns the
153 invoking mock object. Used in conjunction with fake_module(), you
154 can force the tested unit to work with the mock object instead.
155
156 $mock->fake_module( 'CGI' );
157 $mock->fake_new( 'CGI' );
158
159 use_ok( 'Some::Module' );
160 my $s = Some::Module->new();
161 is( $s->{_cgi}, $mock,
162 'new() should create and store a new CGI object' );
163
164 • "set_always(name, value)"
165
166 Adds a method of the specified name that always returns the
167 specified value.
168
169 • "set_true(name_1, name_2, ... name_n)"
170
171 Adds a method of the specified name that always returns a true
172 value. This can take a list of names.
173
174 • "set_false(name_1, name_2, ... name_n)"
175
176 Adds a method of the specified name that always returns a false
177 value. (Since it installs an empty subroutine, the value should be
178 false in both scalar and list contexts.) This can take a list of
179 names.
180
181 • "set_list(name, [ item1, item2, ... ]"
182
183 Adds a method that always returns a given list of values. It takes
184 some care to provide a list and not an array, if that's important
185 to you.
186
187 • "set_series(name, [ item1, item2, ... ]"
188
189 Adds a method that will return the next item in a series on each
190 call. This can help to test error handling, by forcing a failure
191 on the first method call and then subsequent successes. Note that
192 the series does not repeat; it will eventually run out.
193
194 • "set_bound(name, reference)"
195
196 Adds a method bound to a variable. Pass in a reference to a
197 variable in your test. When you change the variable, the return
198 value of the new method will change as well. This is often handier
199 than replacing mock methods.
200
201 • "set_isa( name1, name2, ... namen )"
202
203 Adds an apparent parent to the module, so that calling isa() on the
204 mock will return true appropriately. Sometimes you really need
205 this.
206
207 • remove(name)
208
209 Removes a named method.
210
211 Checking Your Mocks
212
213 • can( $method_name )
214
215 Returns a subroutine reference if this particular mocked object can
216 handle the named method, false otherwise.
217
218 • isa( $class_name )
219
220 Returns true if the invocant object mocks a particular class. You
221 must have used set_isa() first.
222
223 • called(name)
224
225 Checks to see if something has called a named method on the object.
226 This returns a boolean value. The current implementation does not
227 scale especially well, so use this sparingly if you need to search
228 through hundreds of calls.
229
230 • clear()
231
232 Clears the internal record of all method calls on the object. It's
233 handy to do this every now and then. Note that this does not
234 affect the mocked methods, only all of the methods called on the
235 object to this point.
236
237 It's handy to clear() methods in between series of tests. That
238 makes it much easier to call next_method() without having to skip
239 over the calls from the last set of tests.
240
241 • "next_call([ position ])"
242
243 Returns the name and argument list of the next mocked method called
244 on an object, in list context. In scalar context, returns only the
245 method name. There are two important things to know about this
246 method. First, it starts at the beginning of the call list. If
247 your code runs like this:
248
249 $mock->set_true( 'foo' );
250 $mock->set_true( 'bar' );
251 $mock->set_true( 'baz' );
252
253 $mock->foo();
254 $mock->bar( 3, 4 );
255 $mock->foo( 1, 2 );
256
257 Then you might see output of:
258
259 my ($name, $args) = $mock->next_call();
260 print "$name (@$args)";
261
262 # prints 'foo'
263
264 $name = $mock->next_call();
265 print $name;
266
267 # prints 'bar'
268
269 ($name, $args) = $mock->next_call();
270 print "$name (@$args)";
271
272 # prints 'foo 1 2'
273
274 If you provide an optional number as the position argument, the
275 method will skip that many calls, returning the data for the last
276 one skipped.
277
278 $mock->foo();
279 $mock->bar();
280 $mock->baz();
281
282 $name = $mock->next_call();
283 print $name;
284
285 # prints 'foo'
286
287 $name = $mock->next_call( 2 );
288 print $name
289
290 # prints 'baz'
291
292 When it reaches the end of the list, it returns undef. This is
293 probably the most convenient method in the whole module, but for
294 the sake of completeness and backwards compatibility (it takes me a
295 while to reach the truest state of laziness!), there are several
296 other methods.
297
298 • call_pos(position)
299
300 Returns the name of the method called on the object at a specified
301 position. This is handy if you need to test a certain order of
302 calls. For example:
303
304 Some::Function( $mock );
305 is( $mock->call_pos(1), 'setup',
306 'Function() should first call setup()' );
307 is( $mock->call_pos(-1), 'end',
308 '... and last call end()' );
309
310 Positions can be positive or negative. Please note that the first
311 position is, in fact, 1. (This may change in the future. I like
312 it, but am willing to reconsider.)
313
314 • call_args(position)
315
316 Returns a list of the arguments provided to the method called at
317 the appropriate position. Following the test above, one might say:
318
319 is( ($mock->call_args(1))[0], $mock,
320 '... passing the object to setup()' );
321 is( scalar $mock->call_args(-1), 0,
322 '... and no args to end()' );
323
324 • "call_args_pos(call position, argument position)"
325
326 Returns the argument at the specified position for the method call
327 at the specified position. One might rewrite the first test of the
328 last example as:
329
330 is( $mock->call_args_pos(1, 1), $mock,
331 '... passing the object to setup()');
332
333 • "call_args_string(position, [ separator ])"
334
335 Returns a stringified version of the arguments at the specified
336 position. If no separator is given, they will not be separated.
337 This can be used as:
338
339 is( $mock->call_args_string(1), "$mock initialize",
340 '... passing object, initialize as arguments' );
341
342 • "called_ok(method name, [ test name ])"
343
344 Tests to see whether a method of the specified name has been called
345 on the object. This and the following methods use Test::Builder,
346 so they integrate nicely with a test suite built around
347 Test::Simple, Test::More, or anything else compatible:
348
349 $mock->foo();
350 $mock->called_ok( 'foo' );
351
352 A generic default test name is provided.
353
354 • "called_pos_ok(position, method name, [ test name ])"
355
356 Tests to see whether the named method was called at the specified
357 position. A default test name is provided.
358
359 • "called_args_pos_is(method position, argument position, expected, [
360 test name ])"
361
362 Tests to see whether the argument at the appropriate position of
363 the method in the specified position equals a specified value. A
364 default, rather non-descript test name is provided.
365
366 • "called_args_string_is(method position, separator, expected, [ test
367 name ])"
368
369 Joins together all of the arguments to a method at the appropriate
370 position and matches against a specified string. A generically
371 bland test name is provided by default. You can probably do much
372 better.
373
374 • check_class_loaded( $class_name )
375
376 Attempts to determine whether you have a class of the given name
377 loaded and compiled. Returns true or false.
378
379 Logging
380
381 Test::MockObject logs all mocked methods by default. Sometimes you
382 don't want to do this. To prevent logging all calls to a given method,
383 prepend the name of the method with "-" when mocking it.
384
385 That is:
386
387 $mock->set_true( '-foo', 'bar' );
388
389 will set mock both foo() and bar(), causing both to return true.
390 However, the object will log only calls to bar(), not foo(). To log
391 foo() again, merely mock it again without the leading "-":
392
393 $mock->set_true( 'foo' );
394
395 $mock will log all subsequent calls to foo() again.
396
397 Subclassing
398
399 There are two methods provided for subclassing:
400
401 • "dispatch_mocked_method( $method_name, @_ )"
402
403 This method determines how to call a method (named as $method_name)
404 not available in this class. It also controls logging. You may or
405 may not find it useful, but I certainly take advantage of it for
406 Test::MockObject::Extends.
407
408 • "log_call( $method_name, @_ )"
409
410 This method tracks the call of the named method and its arguments.
411
413 • Add a factory method to avoid namespace collisions (soon)
414
415 • Add more useful methods (catch import()?)
416
418 chromatic, <chromatic at wgz dot org>
419
420 Thanks go to Curtis 'Ovid' Poe, as well as ONSITE! Technology, Inc.,
421 for finding several bugs and providing several constructive
422 suggestions.
423
424 Jay Bonci also found a false positive in called_ok(). Thanks!
425
426 Chris Winters was the first to report I'd accidentally scheduled 0.12
427 for deletion without uploading a newer version. He also gave useful
428 feedback on Test::MockObject::Extends.
429
430 Stevan Little provided the impetus and code for set_isa().
431
432 Nicholas Clark found a documentation error.
433
434 Mutant suggested a potential problem with fake_module().
435
437 perl, Test::Tutorial, Test::More,
438 http://www.perl.com/pub/a/2001/12/04/testing.html, and
439 http://www.perl.com/pub/a/2002/07/10/tmo.html.
440
442 Copyright (c) 2002 - 2016 by chromatic <chromatic at wgz dot org>.
443
444 This program is free software; you can use, modify, and redistribute it
445 under the same terms as Perl 5.24 itself.
446
447 See http://www.perl.com/perl/misc/Artistic.html
448
449
450
451perl v5.36.0 2023-01-20 Test::MockObject(3)