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