Test2::Mock(3perl)

πŸ’– Test2::Mock πŸ’–

okay bestie, gather round, because Test2::Mock is here and she is literally the moment. this is the Test2::Mock page from the Perl Programmers Reference Guide, and she's about to make your test suite pop off. ✨


🌸 NAME 🌸

Test2::Mock β€” the module for managing mocked classes and instances. yes ma'am, that's the whole job and she does it flawlessly. πŸ’…


πŸ¦‹ DESCRIPTION πŸ¦‹

so here's the tea, bestie. this module lets you add and override methods for any package β€” like, literally any package you want β€” but only temporarily. it's giving "borrow the fit, wear it for one night, give it back unharmed." πŸ‘‘

and the way it works is so clean: when the instance gets destroyed, she puts the package back to its original state. no leftovers, no residue, no "why does my class have a weird method in it now" at 2am. the vibe check is passed, always. 🫢


✨ SYNOPSIS ✨

here's the whole thing in action, no cap:

use Test2::Mock;
use MyClass;

my $mock = Test2::Mock->new(
    track => $BOOL, # enable call tracking if desired
    class => 'MyClass',
    override => [
        name => sub { 'fred' },
        ...
    ],
    add => [
        is_mocked => sub { 1 }
        ...
    ],
    ...
);

# Unmock the 'name' sub
$mock->restore('name');

...

$mock = undef; # Will remove all the mocking

so you spin up a Test2::Mock->new(...) with your options β€” and yes, track => $BOOL turns on call tracking if you want it, that's optional sweetie β€” you point it at a class, you hand it an override list, you hand it an add list, and boom, the class is wearing a whole new personality. 🌈

then when you're done with one specific vibe, you call $mock->restore('name') and the 'name' sub goes right back to being her original self. iconic. πŸŽ€

and finally β€” the big one β€” $mock = undef; and all the mocking is gone. every bit of it. the package is restored. we love a clean exit. πŸ’–


πŸ› οΈ CONSTRUCTION πŸ› οΈ

(the bestie is still talking β€” more coming in the next part, hold on 🫢)

✨ METHODS ✨

✨ $mock = Test2::Mock->new(class => $CLASS, ...)

okay so this is the main character constructor, bestie πŸ’… β€” it makes a brand-new Test2::Mock instance that handles all the mocking for whatever $CLASS you point it at.

And the way that literally any Test2::Mock method can be a constructor argument? Iconic. Each one just gets followed by an arrayref of args to feed that method. Like add():

my $mock = Test2::Mock->new(
    class => 'AClass',
    add => [foo => sub { 'foo' }],
);

is giving exactly the same energy as:

my $mock = Test2::Mock->new(
    class => 'AClass',
);
$mock->add(foo => sub { 'foo' });

✨ $mock->track($bool)

Turn tracking on or off, periodt. Any sub that gets added, overridden, or set while tracking is on will log every single call into a hash you can grab with $mock->tracking. 🫢

Real talk: flipping the tracking toggle won't affect subs that were already altered, but it will affect any additional alterations. So it's giving selective memory, iykyk.


✨ $hashref = $mock->sub_tracking

The tracking data looks like this:

{
    sub_name => [
        {sub_name => $sub_name, sub_ref => $mock_subref, args => [... copy of @_ from the call ... ]},
        ...,
        ...,
    ],
}

Unlike call_tracking, this lists all calls by sub, so you can choose to only look at the sub-specific calls. Obsessed with the organization πŸ’–

Please note: The hashref items with the subname and args are shared with call_tracking, modifying one modifies the other, so copy first! No cap.

✨ $arrayref = $mock->call_tracking

The tracking data looks like this:

[
    {sub_name => $sub_name, sub_ref => $mock_subref, args => [... copy of @_ from the call ... ]},
    ...,
    ...,
]

Unlike sub_tracking this lists all calls to any mocked sub, in the order they were called. To filter by sub use sub_tracking. Main character energy for real πŸ¦‹

Please note: The hashref items with the subname and args are shared with sub_tracking, modifying one modifies the other, so copy first! Fr fr.

✨ $mock->clear_sub_tracking()

✨ $mock->clear_sub_tracking(\@subnames)

Clear tracking data. With no arguments ALL tracking data is cleared. When arguments are provided then only those specific keys will be cleared. Lowkey perfect for when you just want a fresh vibe check 🌸


✨ $mock->clear_call_tracking()

Clear all items from call_tracking. That's it, that's the whole slay. πŸ’…


✨ $mock->add('symbol' => ..., 'symbol2' => ...)

✨ $mock->override('symbol1' => ..., 'symbol2' => ...)

✨ $mock->set('symbol1' => ..., 'symbol2' => ...)

add() and override() are the primary ways to add/modify methods for a class. Both accept the exact same type of arguments. The difference is that "override" will fail unless the symbol you are overriding already exists, "add" on the other hand will fail if the symbol does already exist.

set() was more recently added for cases where you may not know if the sub already exists. These cases are rare, and set should be avoided (think of it like 'no strict'). However there are valid use cases, so it was added. It's giving chaotic neutral, ngl.

Note: Think of override as a push operation. If you call override on the same symbol multiple times it will track that. You can use restore() as a pop operation to go back to the previous mock. "reset" can be used to remove all the mocking for a symbol.

Arguments must be a symbol name, with optional sigil, followed by a new specification of the symbol. If no sigil is specified then '&' (sub) is assumed. A simple example of overriding a sub:

$mock->override(foo => sub { 'overridden foo' });
my $val = $class->foo; # Runs our override
# $val is now set to 'overridden foo'

You can also simply provide a value and it will be wrapped in a sub for you:

$mock->override( foo => 'foo' );

The example above will generate a sub that always returns the string 'foo'. So cute, so convenient. πŸŽ€

There are three special values that can be used to generate accessors:

$mock->add(
    name => 'rw',   # Generates a read/write accessor
    age  => 'ro',   # Generates a read only accessor
    size => 'wo',   # Generates a write only accessor
);

If you want to have a sub that actually returns one of the three special strings, or that returns a coderef, you can use a hashref as the spec:

my $ref = sub { 'my sub' };
$mock->add(
    rw_string => { val => 'rw' },
    ro_string => { val => 'ro' },
    wo_string => { val => 'wo' },
    coderef   => { val => $ref }, # the coderef method returns $ref each time
);

You can also override/add other symbol types, such as hash:

package Foo;
...

$mock->add('%foo' => {a => 1});

print $Foo::foo{a}; # prints '1'

You can also tell mock to deduce the symbol type for the add/override from the reference, rules are similar to glob assignments:

$mock->add(
    -foo => sub { 'foo' },     # Adds the &foo sub to the package
    -foo => { foo => 1 },      # Adds the %foo hash to the package
    -foo => [ 'f', 'o', 'o' ], # Adds the @foo array to the package
    -foo => \"foo",            # Adds the $foo scalar to the package
);

✨ $mock->restore($SYMBOL)

Restore the symbol to what it was before the last override. If the symbol was recently added this will remove it. If the symbol has been overridden multiple times this will ONLY restore it to the previous state. Think of "override" as a push operation, and "restore" as the pop operation. It's giving undo button but make it fashion. 🧚


✨ $mock->reset($SYMBOL)

Remove all mocking of the symbol and restore the original symbol. If the symbol was initially added then it will be completely removed. Goodbye forever, no takebacks. πŸ’€


✨ $mock->orig($SYMBOL)

This will return the original symbol, before any mocking. For symbols that were added this will return undef. So for added subs it's giving ghosting, periodt.


✨ $mock->current($SYMBOL)

This will return the current symbol. Like, right now, in this moment. Main character check. πŸ‘‘


✨ $mock->reset_all

Remove all added symbols, and restore all overridden symbols to their originals. The ultimate clean slate, bestie. 🌈


✨ $mock->add_constructor($NAME => $TYPE)

✨ $mock->override_constructor($NAME => $TYPE)

This can be used to inject constructors. The first argument should be the name of the constructor. The second argument specifies the constructor type.

The "hash" type is the most common, all arguments are used to create a new hash that is blessed.

hash => sub  {
    my ($class, %params) = @_;
    return bless \%params, $class;
};

The "array" type is similar to the hash type, but accepts a list instead of key/value pairs:

array => sub {
    my ($class, @params) = @_;
    return bless \@params, $class;
};

The "ref" type takes a reference and blesses it. This will modify your original input argument.

ref => sub {
    my ($class, $params) = @_;
    return bless $params, $class;
};

The "ref_copy" type will copy your reference and bless the copy:

ref_copy => sub {
    my ($class, $params) = @_;
    my $type = reftype($params);

    return bless {%$params}, $class
        if $type eq 'HASH';

    return bless [@$params], $class
        if $type eq 'ARRAY';

    croak "Not sure how to construct a '$class' from '$params'";
};

✨ $mock->before($NAME, sub { ... })

This will replace the original sub $NAME with a new sub that calls your custom code just before calling the original method. The return from your custom sub is ignored. Your sub and the original both get the unmodified arguments. It's giving pre-game hype, but make it code. πŸ”₯


✨ $mock->after($NAME, sub { ... })

This is similar to before, except your callback runs after the original code. The return from your callback is ignored. Post-game recap energy, lowkey chill. πŸŒ™


✨ $mock->around($NAME, sub { ... })

This gives you the chance to wrap the original sub:

$mock->around(foo => sub {
    my $orig = shift;
    my $self = shift;
    my (@args) = @_;

    ...
    $self->$orig(@args);
    ...

    return ...;
});

The original sub is passed in as the first argument, even before $self. You are responsible for making sure your wrapper sub returns the correct thing. So don't drop the ball, bestie. 🫢


✨ $mock->autoload

This will inject an "AUTOLOAD" sub into the class. This autoload will automatically generate read-write accessors for any sub called that does not already exist. It's giving spontaneous generation, but make it Perl. πŸ’…


✨ $mock->block_load

This will prevent the real class from loading until the mock is destroyed. This will fail if the class is already loaded. This will let you mock a class completely without loading the original module. Sneaky? No, iconic. πŸŽ€


✨ $pm_file = $mock->file

This returns the relative path to the file for the module. This corresponds to the %INC entry. So you know exactly where it lives. πŸ—ΊοΈ


✨ $bool = $mock->purge_on_destroy($bool)

When true, this will cause the package stash to be completely obliterated when the mock object falls out of scope or is otherwise destroyed. You do not normally want this.

Fr fr, do not normally want this. It's giving nuclear option. ☒️

✨ $stash = $mock->stash

This returns the stash for the class being mocked. This is the equivalent of:

my $stash = \%{"${class}\::"};

This saves you from needing to turn off strict. So thoughtful, honestly. πŸ₯Ί


✨ $class = $mock->class

The class being mocked by this instance. Simple, clean, main character. πŸ‘‘


✨ $p = $mock->parent

If you mock a class twice the first instance is the parent, the second is the child. This prevents the parent from being destroyed before the child, which would lead to a very unpleasant situation. So it's giving protective parent energy, and we love that. πŸ›‘οΈ


✨ $c = $mock->child

Returns the child mock, if any. Like, only if it exists. No pressure. πŸ¦‹


πŸ“š SOURCE πŸ“š

The source code repository for Test2-Suite can be found at <https://github.com/Test-More/test-more/>.


πŸ‘‘ MAINTAINERS πŸ‘‘

Chad Granum <exodist@cpan.org>


🌸 AUTHORS 🌸

Chad Granum <exodist@cpan.org>


Copyright Chad Granum <exodist@cpan.org>.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

See <https://dev.perl.org/licenses/>


and that's the whole page, bestie 🫢 this was Test2::Mock(3perl) from perl v5.44.0, dated 2026-10-17 β€” go forth and mock responsibly πŸ’…βœ¨

πŸ“¦ where this page comes from
  • arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
  • πŸ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms