Test2::Mock(3) | Perl Programmers Reference Guide | Test2::Mock(3) |
Test2::Mock - Module for managing mocked classes and instances.
This module lets you add and override methods for any package temporarily. When the instance is destroyed it will restore the package to its original state.
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
Any "Test2::Mock" method can be used as a constructor argument, each should be followed by an arrayref of arguments to be used within the method. For instance the add() method:
my $mock = Test2::Mock->new( class => 'AClass', add => [foo => sub { 'foo' }], );
is identical to this:
my $mock = Test2::Mock->new( class => 'AClass', ); $mock->add(foo => sub { 'foo' });
{ 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.
Please note: The hashref items with the subname and args are shared with call_tracking, modifying one modifies the other, so copy first!
[ {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.
Please note: The hashref items with the subname and args are shared with sub_tracking, modifying one modifies the other, so copy first!
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.
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'.
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 );
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->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.
my $stash = \%{"${class}\::"};
This saves you from needing to turn off strict.
The source code repository for Test2-Suite can be found at <https://github.com/Test-More/Test2-Suite/>.
Copyright 2018 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/>
2024-04-28 | perl v5.40.0 |