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