Test::MockModule(3pm)

NAME
Test::MockModule - Override subroutines in a module for unit testing

SYNOPSIS
        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 { ... });

DESCRIPTION
"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.

STRICT MODE
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!

GLOBAL STRICT MODE
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.

METHODS

new($package[, %options])
    Returns a singleton-per-package mock object. Two calls to "Test::MockModule->new('Foo')" return the same object as long as the first one is still alive; this preserves the long-standing pre-v0.181 contract that the documented "$mock->original" from-inside-closure pattern depends on (see GH #83).

    Pass "distinct => 1" to opt into the v0.181 GH #48 semantics -- each call returns a fresh object, multiple mock objects coexist on the same package, and the per-sub stack handles multi-mock layering:

            my $m1 = Test::MockModule->new('Module::Name', distinct => 1);
            my $m2 = Test::MockModule->new('Module::Name', distinct => 1);
            # $m1 and $m2 are independent. Tests that need this layering must
            # opt in explicitly.

    Under "distinct" mode the most recent "mock"/"redefine" call wins regardless of stack position; when a mock object is destroyed, the layer below it on the stack is reactivated; when all mock objects for a subroutine are destroyed, the original subroutine is restored.

    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);

    GH #83 caveat for distinct mode: a closure that captures $mock (typically by calling "$mock->original(...)" inside the mock body) prevents "DESTROY" from firing when $mock goes out of scope, so the mock leaks past its lexical scope. The default (singleton) mode makes this leak harmless by re-using the same object on subsequent new() calls. Under "distinct => 1", prefer the class-method form "Test::MockModule->original_for($pkg, $sub)" from inside closures so they capture only strings, or capture "$mock->original(...)" in a lexical before calling mock().

get_package()
    Returns the target package name for the mocked subroutines

is_mocked($subroutine)
    Returns a boolean value indicating whether or not the subroutine is currently mocked

mocked_subs()
    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')

mock($subroutine => \&coderef)
    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

redefine($subroutine)
    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(...);

define($subroutine)
    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(...);

original($subroutine)
    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, @_);
                    }
            });

original_for($package, $subroutine)
    Class-method counterpart to original(). Returns the truly-original coderef for "$package::$subroutine" from the per-package registry, or the live sub via the symbol table if not currently mocked. Returns "undef" if no sub by that name exists. Croaks on invalid package or sub names.

    The motivating use case is letting closures reach the original sub without capturing $mock -- the closure-capture pattern that drives the GH #83 leak under "distinct => 1" mode:

            my $mock = Test::MockModule->new('MyModule', distinct => 1);
            $mock->mock('greet', sub {
                    # Closure captures only strings -- $mock can be GC'd at scope end
                    return Test::MockModule
                            ->original_for('MyModule', 'greet')->(@_) . '_suffix';
            });

    For stacked mocks, returns the truly-original (pre-any-mock) coderef, not the layer below.

unmock($subroutine [, ...])
    Restores the original $subroutine. You can specify a list of subroutines to unmock() in one go.

unmock_all()
    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.

noop($subroutine [, ...])
    Given a list of subroutine names, mocks each of them with a no-op subroutine that returns 1. Handy for mocking methods you want to ignore!

    The 1 return value is part of the public contract of this method (see GH #81) -- callers in the wild rely on it being truthy.

        # Neuter a list of methods in one go
        $module->noop('purge', 'updated');

mock_all(%options)
    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:

    noop => 1
        Mock all subroutines with a no-op sub that returns 1 instead of dying. This is consistent with noop().

            $module->mock_all(noop => 1);
            Foo->bar();  # returns 1

    handler => \&coderef
        Provide a custom handler for all mocked subroutines.

            $module->mock_all(handler => sub { warn "unexpected call" });

    Returns the current "Test::MockModule" object for chaining.

TRACE
    A stub for Log::Trace

DUMP
    A stub for Log::Trace

MOOSE AND MOUSE SUPPORT
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 and other MOP-less object systems
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.

SEE ALSO
Test::MockObject::Extends

Sub::Override

AUTHORS
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
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.