Section: User Contributed Perl Documentation (3)
Updated: 2008-05-27


Test::MockObject - Perl extension for emulating troublesome interfaces 


  use Test::MockObject;  my $mock = Test::MockObject->new();  $mock->set_true( 'somemethod' );  ok( $mock->somemethod() );  $mock->set_true( 'veritas')         ->set_false( 'ficta' )       ->set_series( 'amicae', 'Sunny', 'Kylie', 'Bella' );


It's a simple program that doesn't use any other modules, and those are easy totest. More often, testing a program completely means faking up input toanother module, trying to coax the right output from something you're notsupposed to be testing anyway.

Testing is a lot easier when you can control the entire environment. WithTest::MockObject, you can get a lot closer.

Test::MockObject allows you to create objects that conform to particularinterfaces with very little code. You don't have to reimplement the behavior,just the input and the output. 


Please note that it is possible to write highly detailed unit tests that passeven when your integration tests may fail. Testing the pieces individuallydoes not excuse you from testing the whole thing together. I consider this tobe a feature.

In cases where you only need to mock one or two pieces of an existing module,consider Test::MockObject::Extends instead. 


None by default. Maybe the Test::Builder accessories, in a future version. 


The most important thing a Mock Object can do is to conform sufficiently to aninterface. For example, if you're testing something that relies on, youmay find it easier to create a mock object that returns controllable resultsat given times than to fake query string input.

The Basics


Creates a new mock object. By default, this is a blessed hash. Pass areference to bless that reference.

    my $mock_array  = Test::MockObject->new( [] );    my $mock_scalar = Test::MockObject->new( \( my $scalar ) );    my $mock_code   = Test::MockObject->new( sub {} );    my $mock_glob   = Test::MockObject->new( \*GLOB );


Your mock object is nearly useless if you don't tell it what it's mocking.This is done by installing methods. You control the output of these mockedmethods. In addition, any mocked method is tracked. You can tell not onlywhat was called, but which arguments were passed. Please note that you cannottrack non-mocked method calls. They will still be allowed, thoughTest::MockObject will carp() about them. This is considered a feature, thoughit may be possible to disable this in the future.

As implied in the example above, it's possible to chain these calls together.Thanks to a suggestion from the fabulous Piers Cawley (CPAN RT #1249), thisfeature came about in version 0.09. Shorter testing code is nice!

"mock(name, coderef)"

Adds a coderef to the object. This allows code to call the named method on theobject. For example, this code:

    my $mock = Test::MockObject->new();    $mock->mock( 'fluorinate',        sub { 'impurifying precious bodily fluids' } );    print $mock->fluorinate;

will print a helpful warning message. Please note that methods are only addedto a single object at a time and not the class. (There is no small similarityto the Self programming language or the Class::Prototyped module.)

This method forms the basis for most of Test::MockObject's testing goodness.

Please Note: this method used to be "add()". Due to its ambiguity, it nowhas a different spelling. For backwards compatibility purposes, add() isavailable, though version 0.07 deprecated it. It goes to some contortions totry to do what you mean, but I make few guarantees.

"fake_module(module name), [ subname =" coderef, ... ]

Note: this method will likely become a separate module in the near future.

Lies to Perl that it has already loaded a named module. This is handy whenproviding a mockup of a real module if you'd like to prevent the actual modulefrom interfering with the nice fakery. If you're mocking Regexp::English,say:

    $mock->fake_module( 'Regexp::English' );

This is both a class and as an object method. Beware that this must take placebefore the actual module has a chance to load. Either wrap it in a BEGIN blockbefore a use or require or place it before a "use_ok()" or "require_ok()"call.

You can optionally add functions to the mocked module by passing them as name=> coderef pairs to "fake_module()". This is handy if you want to test an"import()":

    my $import;    $mock->fake_module(        'Regexp::English',        import => sub { $import = caller }    );    use_ok( 'Regexp::Esperanto' );    is( $import, 'Regexp::Esperanto',        'Regexp::Esperanto should use() Regexp::English' );

If you use "fake_module()" to mock a module that already exists in memory ---one you've loaded elsewhere perhaps, but do not pass any subroutines to mock,this method will throw an exception. This is because if you call theconstructor later on, you probably won't get a mock object back and you'll beconfused.

"fake_new(module name)"

Note: see Test::MockObject::Extends for a better alternative to thismethod.

Provides a fake constructor for the given module that returns the invoking mockobject. Used in conjunction with "fake_module()", you can force the testedunit to work with the mock object instead.

    $mock->fake_module( 'CGI' );    $mock->fake_new( 'CGI' );    use_ok( 'Some::Module' );    my $s = Some::Module->new();    is( $s->{_cgi}, $mock,        'new() should create and store a new CGI object' );
"set_always(name, value)"

Adds a method of the specified name that always returns the specified value.

"set_true(name_1, name_2, ... name_n)"

Adds a method of the specified name that always returns a true value. This cantake a list of names.

"set_false(name_1, name_2, ... name_n)"

Adds a method of the specified name that always returns a false value. (Sinceit installs an empty subroutine, the value should be false in both scalar andlist contexts.) This can take a list of names.

"set_list(name, [ item1, item2, ... ]"

Adds a method that always returns a given list of values. It takes some careto provide a list and not an array, if that's important to you.

"set_series(name, [ item1, item2, ... ]"

Adds a method that will return the next item in a series on each call. Thiscan help to test error handling, by forcing a failure on the first method calland then subsequent successes. Note that the series does not repeat; it willeventually run out.

"set_bound(name, reference)"

Adds a method bound to a variable. Pass in a reference to a variable in yourtest. When you change the variable, the return value of the new method willchange as well. This is often handier than replacing mock methods.

"set_isa( name1, name2, ... namen )"

Adds an apparent parent to the module, so that calling "isa()" on the mockwill return true appropriately. Sometimes you really need this.


Removes a named method.

Checking Your Mocks

"can( $method_name )"

Returns a subroutine reference if this particular mocked object can handle thenamed method, false otherwise.

"isa( $class_name )"

Returns true if the invocant object mocks a particular class. You must haveused "set_isa()" first.


Checks to see if something has called a named method on the object. Thisreturns a boolean value. The current implementation does not scale especiallywell, so use this sparingly if you need to search through hundreds of calls.


Clears the internal record of all method calls on the object. It's handy to dothis every now and then. Note that this does not affect the mocked methods,only all of the methods called on the object to this point.

It's handy to "clear()" methods in between series of tests. That makes itmuch easier to call "next_method()" without having to skip over the calls fromthe last set of tests.

"next_call([ position ])"

Returns the name and argument list of the next mocked method called on anobject, in list context. In scalar context, returns only the method name.There are two important things to know about this method. First, it starts atthe beginning of the call list. If your code runs like this:

    $mock->set_true( 'foo' );    $mock->set_true( 'bar' );    $mock->set_true( 'baz' );    $mock->foo();    $mock->bar( 3, 4 );    $mock->foo( 1, 2 );

Then you might see output of:

    my ($name, $args) = $mock->next_call();    print "$name (@$args)";    # prints 'foo'    $name = $mock->next_call();    print $name;    # prints 'bar'    ($name, $args) = $mock->next_call();    print "$name (@$args)";    # prints 'foo 1 2'

If you provide an optional number as the position argument, the method willskip that many calls, returning the data for the last one skipped.

    $mock->foo();    $mock->bar();    $mock->baz();    $name = $mock->next_call();    print $name;    # prints 'foo'    $name = $mock->next_call( 2 );    print $name    # prints 'baz'

When it reaches the end of the list, it returns undef. This is probably themost convenient method in the whole module, but for the sake of completenessand backwards compatibility (it takes me a while to reach the truest state oflaziness!), there are several other methods.


Returns the name of the method called on the object at a specified position.This is handy if you need to test a certain order of calls. For example:

    Some::Function( $mock );    is( $mock->call_pos(1),  'setup',        'Function() should first call setup()' );    is( $mock->call_pos(-1), 'end',        '... and last call end()' );

Positions can be positive or negative. Please note that the first position is,in fact, 1. (This may change in the future. I like it, but am willing toreconsider.)


Returns a list of the arguments provided to the method called at the appropriateposition. Following the test above, one might say:

    is( ($mock->call_args(1))[0], $mock,        '... passing the object to setup()' );    is( scalar $mock->call_args(-1), 0,        '... and no args to end()' );
"call_args_pos(call position, argument position)"

Returns the argument at the specified position for the method call at thespecified position. One might rewrite the first test of the last example as:

    is( $mock->call_args_pos(1, 1), $mock,        '... passing the object to setup()');
"call_args_string(position, [ separator ])"

Returns a stringified version of the arguments at the specified position. Ifno separator is given, they will not be separated. This can be used as:

    is( $mock->call_args_string(1), "$mock initialize",        '... passing object, initialize as arguments' );
"called_ok(method name, [ test name ])"

Tests to see whether a method of the specified name has been called on theobject. This and the following methods use Test::Builder, so they integratenicely with a test suite built around Test::Simple, Test::More, or anythingelse compatible:

    $mock->foo();    $mock->called_ok( 'foo' );

A generic default test name is provided.

"called_pos_ok(position, method name, [ test name ])"

Tests to see whether the named method was called at the specified position. Adefault test name is provided.

"called_args_pos_is(method position, argument position, expected, [ test name ])"

Tests to see whether the argument at the appropriate position of the method inthe specified position equals a specified value. A default, rathernon-descript test name is provided.

"called_args_string_is(method position, separator, expected, [ test name ])"

Joins together all of the arguments to a method at the appropriate position andmatches against a specified string. A generically bland test name is providedby default. You can probably do much better.

"check_class_loaded( $class_name )"

Attempts to determine whether you have a class of the given name loaded andcompiled. Returns true or false.


Test::MockObject logs all mocked methods by default. Sometimes you don't wantto do this. To prevent logging all calls to a given method, prepend the nameof the method with "-" when mocking it.

That is:

    $mock->set_true( '-foo', 'bar' );

will set mock both "foo()" and "bar()", causing both to return true.However, the object will log only calls to "bar()", not "foo()". To log"foo()" again, merely mock it again without the leading "-":

    $mock->set_true( 'foo' );

$mock will log all subsequent calls to "foo()" again.


There are two methods provided for subclassing:

"dispatch_mocked_method( $method_name, @_ )"

This method determines how to call a method (named as $method_name) notavailable in this class. It also controls logging. You may or may not find ituseful, but I certainly take advantage of it for Test::MockObject::Extends.

"log_call( $method_name, @_ )"

This method tracks the call of the named method and its arguments.



Add a factory method to avoid namespace collisions (soon)
Add more useful methods (catch "import()"?)


chromatic, <chromatic at wgz dot org>

Thanks go to Curtis 'Ovid' Poe, as well as ONSITE! Technology, Inc., forfinding several bugs and providing several constructive suggestions.

Jay Bonci also found a false positive in "called_ok()". Thanks!

Chris Winters was the first to report I'd accidentally scheduled 0.12 fordeletion without uploading a newer version. He also gave useful feedback onTest::MockObject::Extends.

Stevan Little provided the impetus and code for "set_isa()".

Nicholas Clark found a documentation error.

Mutant suggested a potential problem with fake_module(). 


perl, Test::Tutorial, Test::More,,and 


Copyright (c) 2002 - 2008 by chromatic <chromatic at wgz dot org>.

This program is free software; you can use, modify, and redistribute it underthe same terms as Perl 5.10.x itself.





This document was created byman2html,using the manual pages.