Test::MockModule(3pm)

🌸 Test::MockModule β€” the Test::MockModule(3pm) page, bestie edition πŸ’…

User Contributed Perl Documentation Β· 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 { ... });
}

# Back in the strict scope, so mock() dies here
$module->mock('subroutine', sub { ... });

πŸ’– DESCRIPTION πŸ’–

okay so Test::MockModule is literally here to let you temporarily redefine subroutines in other packages, all for the sake of unit testing. no cap, that's the whole vibe. 🫢

A Test::MockModule object gets set up to mock subroutines for one specific module. and here's the iconic part β€” the object remembers the original subroutine so it can just... put it back. easily. like nothing ever happened. πŸ™ˆ This restoration happens automatically when all the MockModule objects for that given module go out of scope, or when you call unmock() on the subroutine. slay. ✨


πŸ‘‘ STRICT MODE πŸ‘‘

ngl, one of the big weaknesses of testing with mocks is that the implementation of the interface you're mocking might change... while your mocks just sit there, untouched, living their best life. 😭 and now you're not even mocking what you thought you were mocking. and your mocks might be hiding bugs that will only get spotted in production. it's giving horror movie.

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, turning it into a fatal runtime error. πŸ’€ Instead, you should define your mocks using redefine() β€” which will only mock things that already exist, and will die if you try to redefine something that doesn't exist. periodt.

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, like so:

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 gonna try and be clever by calling Test::MockModule's import() method at runtime, then what happens is undefined, with results differing from one version of perl to another. What larks! 🌈

πŸ’– METHODS πŸ’–

Bestie, here's the whole method lineup. No skips, no cuts, every detail stays. 🫢

🌟 new($package[, %options]) 🌟

Returns an object that will mock subroutines in the specified $package. That's the whole vibe. πŸ’…

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

🌸 get_package() 🌸

Returns the target package name for the mocked subroutines. iykyk πŸŽ€

🌈 is_mocked($subroutine) 🌈

Returns a boolean value indicating whether or not the subroutine is currently mocked. vibe check: true or false, bestie βœ…

πŸ’… 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. It's giving "instant return value" ✨

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). Important, bestie: the original comes back, not the last fake 😭

🌈 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. Basically: no mocking ghost subs, bestie πŸ‘»

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. Inheritance said "I got you" 🫢

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. Main character energy for edge cases πŸ’…

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. No parent peek, fr fr πŸ™ˆ

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. The real one, the blueprint, the OG πŸ‘‘

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");
# replace all calls to get_path_for using a different argument
$mock->redefine("get_path_for", sub {
        return $mock->original("get_path_for")->("/my/custom/path");
});

# or

$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 $mock->original("get_path_for")->("/my/custom/path");
        } else { # preserve the original arguments
                return $mock->original("get_path_for")->($path, @_);
        }
});

πŸ’œ unmock($subroutine [, ...]) πŸ’œ

Restores the original $subroutine. You can specify a list of subroutines to unmock() in one go. Bye bye, fake versions πŸ‘‹

🌸 unmock_all() 🌸

Restores all the subroutines in the package that were mocked. This is automatically called when all "Test::MockObject" objects for the given package go out of scope. Auto-cleanup, iconic ✨

πŸ“ noop($subroutine [, ...]) πŸ“

Given a list of subroutine names, mocks each of them with a no-op subroutine. Handy for mocking methods you want to ignore! Silence them, bestie 🀫

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

🌈 TRACE 🌈

A stub for Log::Trace. Just a lil stub πŸŽ€

🌈 DUMP 🌈

A stub for Log::Trace. Another lil stub, same energy πŸŽ€

πŸ”₯ 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 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.


That's the whole page, bestie! This gem is from perl v5.42.0, dated 2025-07-25, for Test::MockModule(3pm) β€” go forth and mock responsibly πŸ’…βœ¨

πŸ“¦ where this page comes from