| Test::MockModule - Override subroutines in a module for unit testing |
Test::MockModule - Override subroutines in a module for unit testing
use Module::Name;
use Test::MockModule;
{
my $module = Test::MockModule->new('Module::Name');
$module->mock('subroutine', sub { ... });
Module::Name::subroutine(@args); # mocked
# Same effect, but this will die() if other_subroutine()
# doesn't already exist, which is often desirable.
$module->redefine('other_subroutine', sub { ... });
# This will die() if another_subroutine() is defined.
$module->define('another_subroutine', sub { ... });
}
{
# you can also chain new/mock/redefine/define
Test::MockModule->new('Module::Name')
->mock( one_subroutine => sub { ... })
->redefine( other_subroutine => sub { ... } )
->define( a_new_sub => 1234 );
}
Module::Name::subroutine(@args); # original subroutine
# Working with objects
use Foo;
use Test::MockModule;
{
my $mock = Test::MockModule->new('Foo');
$mock->mock(foo => sub { print "Foo!\n"; });
my $foo = Foo->new();
$foo->foo(); # prints "Foo!\n"
}
# If you want to prevent noop and mock from working, you can
# load Test::MockModule in strict mode.
use Test::MockModule qw/strict/;
my $module = Test::MockModule->new('Module::Name');
# Redefined the other_subroutine or dies if it's not there.
$module->redefine('other_subroutine', sub { ... });
# Dies since you specified you wanted strict mode.
$module->mock('subroutine', sub { ... });
# Turn strictness off in this lexical scope
{
use Test::MockModule 'nostrict';
# ->mock() works now
$module->mock('subroutine', sub { ... });
}
# Assure strict is ALWAYS used.
use Test::MockModule 'global-strict';
# Back in the strict scope, so mock() dies here
$module->mock('subroutine', sub { ... });
Test::MockModule lets you temporarily redefine subroutines in other packages for the purposes of unit testing.
A Test::MockModule object is set up to mock subroutines for a given module. The object remembers the original subroutine so it can be easily restored. This happens automatically when all MockModule objects for the given module go out of scope, or when you unmock() the subroutine.
One of the weaknesses of testing using mocks is that the implementation of the interface that you are mocking might change, while your mocks get left alone. You are not now mocking what you thought you were, and your mocks might now be hiding bugs that will only be spotted in production. To help prevent this you can load Test::MockModule in 'strict' mode:
use Test::MockModule qw(strict);
This will disable use of the mock() method, making it a fatal runtime error. You should instead define mocks using redefine(), which will only mock things that already exist and die if you try to redefine something that doesn't exist.
Strictness is lexically scoped, so you can do this in one file:
use Test::MockModule qw(strict);
...->redefine(...);
and this in another:
use Test::MockModule; # the default is nostrict
...->mock(...);
You can even mix n match at different places in a single file thus:
use Test::MockModule qw(strict);
# here mock() dies
{
use Test::MockModule qw(nostrict);
# here mock() works
}
# here mock() goes back to dieing
use Test::MockModule qw(nostrict);
# and from here on mock() works again
NB that strictness must be defined at compile-time, and set using use. If you think you're going to try and be clever by calling Test::MockModule's import() method at runtime then what happens in undefined, with results differing from one version of perl to another. What larks!
If your particular test suite needs to assure that no developer ever accidentally turns off strict, this is the mode for you
use Test::MockModule 'global-strict';
Setting this mode will cause any later invocation of nostrict to fail on compile. Further, any use of mock at runtime will die if the 'nostrict' mode was invoked prior to global-strict being initially set. While this seems like it might be overkill, this can be important as the number of simultaneous developers increases over time.
Returns a new object that will mock subroutines in the specified $package. Each call to new() returns a distinct object, even for the same package. Multiple mock objects can coexist for the same package, each tracking its own mocked subroutines independently. When a mock object is destroyed (or goes out of scope), only the subroutines it mocked are restored.
If two objects mock the same subroutine, the most recent mock/redefine call wins regardless of stack position. When a mock object is destroyed (or unmocked), the layer below it on the stack is reactivated. When all mock objects for a subroutine are destroyed, the original subroutine is restored.
Note: prior to v0.180.x, new() returned the same object on subsequent calls for an already-mocked package. Tests relying on that singleton behavior should be updated.
If there is no $VERSION defined in $package, the module will be automatically loaded. You can override this behaviour by setting the no_auto option:
my $mock = Test::MockModule->new('Module::Name', no_auto => 1);
Returns the target package name for the mocked subroutines
Returns a boolean value indicating whether or not the subroutine is currently mocked
Returns a sorted list of the subroutine names that are currently mocked for this module. Useful for debugging complex test setups.
my $mock = Test::MockModule->new('Module::Name');
$mock->mock('foo', sub { 1 });
$mock->mock('bar', sub { 2 });
my @mocked = $mock->mocked_subs; # ('bar', 'foo')
Temporarily replaces one or more subroutines in the mocked module. A subroutine can be mocked with a code reference or a scalar. A scalar will be recast as a subroutine that returns the scalar.
Returns the current Test::MockModule object, so you can chain new with mock.
my $mock = Test::MockModule->new(...)->mock(...);
The following statements are equivalent:
$module->mock(purge => 'purged');
$module->mock(purge => sub { return 'purged'});
When dealing with references, things behave slightly differently. The following statements are NOT equivalent:
# Returns the same arrayref each time, with the localtime() at time of mocking
$module->mock(updated => [localtime()]);
# Returns a new arrayref each time, with up-to-date localtime() value
$module->mock(updated => sub { return [localtime()]});
The following statements are in fact equivalent:
my $array_ref = [localtime()]
$module->mock(updated => $array_ref)
$module->mock(updated => sub { return $array_ref });
However, undef is a special case. If you mock a subroutine with undef it will install an empty subroutine
$module->mock(purge => undef);
$module->mock(purge => sub { });
rather than a subroutine that returns undef:
$module->mock(purge => sub { undef });
You can call mock() for the same subroutine many times, but when you call unmock(), the original subroutine is restored (not the last mocked instance).
MOCKING + EXPORT
If you are trying to mock a subroutine exported from another module, this may not behave as you initially would expect, since Test::MockModule is only mocking at the target module, not anything importing that module. If you mock the local package, or use a fully qualified function name, you will get the behavior you desire:
use Test::MockModule;
use Test::More;
use POSIX qw/strftime/;
my $posix = Test::MockModule->new("POSIX");
$posix->mock("strftime", "Yesterday");
is strftime("%D", localtime(time)), "Yesterday", "`strftime` was mocked successfully"; # Fails
is POSIX::strftime("%D", localtime(time)), "Yesterday", "`strftime` was mocked successfully"; # Succeeds
my $main = Test::MockModule->new("main", no_auto => 1);
$main->mock("strftime", "today");
is strftime("%D", localtime(time)), "today", "`strftime` was mocked successfully"; # Succeeds
If you are trying to mock a subroutine that was exported into a module that you're trying to test, rather than mocking the subroutine in its originating module, you can instead mock it in the module you are testing:
package MyModule;
use POSIX qw/strftime/;
sub minus_twentyfour
{
return strftime("%a, %b %d, %Y", localtime(time - 86400));
}
package main;
use Test::More;
use Test::MockModule;
my $posix = Test::MockModule->new("POSIX");
$posix->mock("strftime", "Yesterday");
is MyModule::minus_twentyfour(), "Yesterday", "`minus-twentyfour` got mocked"; # fails
my $mymodule = Test::MockModule->new("MyModule", no_auto => 1);
$mymodule->mock("strftime", "Yesterday");
is MyModule::minus_twentyfour(), "Yesterday", "`minus-twentyfour` got mocked"; # succeeds
The same behavior as mock(), but this will preemptively check to be sure that all passed subroutines actually exist. This is useful to ensure that if a mocked module's interface changes the test doesn't just keep on testing a code path that no longer behaves consistently with the mocked behavior.
Note that redefine is also now checking if one of the parent provides the sub and will not die if it's available in the chain.
Returns the current Test::MockModule object, so you can chain new with redefine.
my $mock = Test::MockModule->new(...)->redefine(...);
The reverse of redefine, this will fail if the passed subroutine exists. While this use case is rare, there are times where the perl code you are testing is inspecting a package and adding a missing subroutine is actually what you want to do.
By using define, you're asserting that the subroutine you want to be mocked should not exist in advance.
Note: define does not check for inheritance like redefine.
Returns the current Test::MockModule object, so you can chain new with define.
my $mock = Test::MockModule->new(...)->define(...);
Returns the original (unmocked) subroutine. If the subroutine is not currently mocked, returns the existing subroutine directly instead of warning. This makes it safe to call original() before or after mocking.
Here is a sample how to wrap a function with custom arguments using the original subroutine. This is useful when you cannot (do not) want to alter the original code to abstract one hardcoded argument pass to a function.
package MyModule;
sub sample {
return get_path_for("/a/b/c/d");
}
sub get_path_for {
... # anything goes there...
}
package main;
use Test::MockModule;
my $mock = Test::MockModule->new("MyModule");
# capture the original before mocking to avoid closing over $mock
my $orig_get_path = $mock->original("get_path_for");
# replace all calls to get_path_for using a different argument
$mock->redefine("get_path_for", sub {
return $orig_get_path->("/my/custom/path");
});
# or
my $orig_get_path = $mock->original("get_path_for");
$mock->redefine("get_path_for", sub {
my $path = shift;
if ( $path && $path eq "/a/b/c/d" ) {
# only alter calls with path set to "/a/b/c/d"
return $orig_get_path->("/my/custom/path");
} else { # preserve the original arguments
return $orig_get_path->($path, @_);
}
});
Restores the original $subroutine. You can specify a list of subroutines to unmock() in one go.
Restores all the subroutines in the package that were mocked. This is automatically called when all Test::MockModule objects for the given package go out of scope.
Given a list of subroutine names, mocks each of them with a no-op subroutine. Handy for mocking methods you want to ignore!
# Neuter a list of methods in one go
$module->noop('purge', 'updated');
Mocks all subroutines in the target package that are not already mocked. By default, each mocked subroutine will die when called, making it easy to catch unexpected calls during testing.
my $module = Test::MockModule->new('Foo');
$module->mock_all();
Foo->bar(); # dies: "Foo::bar was not mocked"
The import subroutine is always skipped.
Options:
Mock all subroutines with a no-op (empty sub) instead of dying.
$module->mock_all(noop => 1);
Foo->bar(); # silently does nothing
Provide a custom handler for all mocked subroutines.
$module->mock_all(handler => sub { warn "unexpected call" });
Returns the current Test::MockModule object for chaining.
A stub for Log::Trace
A stub for Log::Trace
When the target package's metaclass is a Class::MOP::Class (Moose) or Mouse::Meta::Class (Mouse), Test::MockModule registers mocks with the meta-object via add_method in addition to installing them in the symbol table. This makes mocked methods visible to:
Moose role requires checks (including dynamic role application via "apply_all_roles" in Moose::Util).
Method modifier resolution (around, before, after) on subclasses loaded after the mock is installed.
Other MOP-driven introspection that walks get_method / get_method_list.
unmock reverses the registration: if the original method existed on the class itself, it is restored via add_method; if the method was inherited (or absent) before mocking, it is removed via remove_method so inheritance lookup falls back to the parent. For Mouse classes (which lack a public remove_method on Mouse::Meta::Class), the mock entry is purged from the meta-class's internal method cache directly to achieve the same effect.
If the target class is immutable ($meta->is_immutable is true), Test::MockModule falls back to symbol-table-only behavior and emits a warning. Call Pkg->meta->make_mutable before mocking if you need MOP-aware behavior on an immutable class.
Moo, Role::Tiny, and Object::Pad are not detected and not specially handled. Mocks on Moo classes still work for direct calls but will not be seen by role-application or method-modifier resolution for classes that consume Moo roles. As a workaround, mock the underlying package directly with no_auto => 1 and explicit load ordering, or convert the affected class to Moose.
Current Maintainer: Geoff Franks <gfranks@cpan.org>
Original Author: Simon Flack <simonflk _AT_ cpan.org>
Lexical scoping of strictness: David Cantrell <david@cantrell.org.uk>
Copyright 2004 Simon Flack <simonflk _AT_ cpan.org>. All rights reserved
You may distribute under the terms of either the GNU General Public License or the Artistic License, as specified in the Perl README file.
| Test::MockModule - Override subroutines in a module for unit testing |