| Test2::Tools::Mock(3) | User Contributed Perl Documentation | Test2::Tools::Mock(3) |
Test2::Tools::Mock - Class/Instance mocking for Test2.
Mocking is often an essential part of testing. This library covers some of the most common mocking needs. This plugin is heavily influenced by Mock::Quick, but with an improved API. This plugin is also intended to play well with other plugins in ways Mock::Quick would be unable to.
my $mock = mock 'Some::Class' => (
track => $BOOL, # Enable/Disable tracking on subs defined below
add => [
new_method => sub { ... },
],
override => [
replace_method => sub { ... },
],
set => [
replace_or_inject => sub { ... },
],
track => $bool, # enable/disable tracking again to affect mocks made after this point
..., # Argument keys may be repeated
);
Some::Class->new_method(); # Calls the newly injected method
Some::Class->replace_method(); # Calls our replacement method.
$mock->override(...) # Override some more
$mock = undef; # Undoes all the mocking, restoring all original methods.
my $simple_mock = mock {} => (
add => [
is_active => sub { ... }
]
);
$simple_mock->is_active(); # Calls our newly mocked method.
The second form calls the specified method on the current build. This second form delegates to "mock_do()".
DEFINING MOCKS
Arguments can be any method available to Test2::Mock followed by an argument. If the very first argument is a hashref then it will be blessed as your new object.
If you provide a coderef instead of key/value pairs, the coderef will be run to build the mock. (See the "BUILDING MOCKS" section).
Arguments can be any method available to Test2::Mock followed by an argument. If the very first argument is a hashref then it will be blessed as your new object.
If you provide a coderef instead of key/value pairs, the coderef will be run to build the mock. (See the "BUILDING MOCKS" section).
BUILDING MOCKS
METHOD GENERATORS
$sub = sub {
my $self = shift;
($self->{$field}) = @_ if @_;
return $self->{$field};
};
$sub = sub {
my $self = shift;
return $self->{$field};
};
$sub = sub {
my $self = shift;
($self->{$field}) = @_;
};
my $mock = mock(...);
Mock objects are instances of Test2::Mock. See it for their methods.
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/>
| 2020-10-22 | perl v5.34.0 |