.\" -*- mode: troff; coding: utf-8 -*- .\" Automatically generated by Pod::Man v6.0.2 (Pod::Simple 3.45) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>. .ie n \{\ . ds C` "" . ds C' "" 'br\} .el\{\ . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" .\" Required to disable full justification in groff 1.23.0. .if n .ds AD l .\" ======================================================================== .\" .IX Title "Test::MockModule 3pm" .TH Test::MockModule 3pm 2026-06-29 "perl v5.42.2" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH NAME Test::MockModule \- Override subroutines in a module for unit testing .SH SYNOPSIS .IX Header "SYNOPSIS" .Vb 2 \& use Module::Name; \& use Test::MockModule; \& \& { \& my $module = Test::MockModule\->new(\*(AqModule::Name\*(Aq); \& $module\->mock(\*(Aqsubroutine\*(Aq, sub { ... }); \& Module::Name::subroutine(@args); # mocked \& \& # Same effect, but this will die() if other_subroutine() \& # doesn\*(Aqt already exist, which is often desirable. \& $module\->redefine(\*(Aqother_subroutine\*(Aq, sub { ... }); \& \& # This will die() if another_subroutine() is defined. \& $module\->define(\*(Aqanother_subroutine\*(Aq, sub { ... }); \& } \& \& { \& # you can also chain new/mock/redefine/define \& \& Test::MockModule\->new(\*(AqModule::Name\*(Aq) \& \->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(\*(AqFoo\*(Aq); \& $mock\->mock(foo => sub { print "Foo!\en"; }); \& \& my $foo = Foo\->new(); \& $foo\->foo(); # prints "Foo!\en" \& } \& \& # 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(\*(AqModule::Name\*(Aq); \& \& # Redefined the other_subroutine or dies if it\*(Aqs not there. \& $module\->redefine(\*(Aqother_subroutine\*(Aq, sub { ... }); \& \& # Dies since you specified you wanted strict mode. \& $module\->mock(\*(Aqsubroutine\*(Aq, sub { ... }); \& \& # Turn strictness off in this lexical scope \& { \& use Test::MockModule \*(Aqnostrict\*(Aq; \& # \->mock() works now \& $module\->mock(\*(Aqsubroutine\*(Aq, sub { ... }); \& } \& \& # Assure strict is ALWAYS used. \& use Test::MockModule \*(Aqglobal\-strict\*(Aq; \& \& # Back in the strict scope, so mock() dies here \& $module\->mock(\*(Aqsubroutine\*(Aq, sub { ... }); .Ve .SH DESCRIPTION .IX Header "DESCRIPTION" \&\f(CW\*(C`Test::MockModule\*(C'\fR lets you temporarily redefine subroutines in other packages for the purposes of unit testing. .PP A \f(CW\*(C`Test::MockModule\*(C'\fR 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 \f(CWunmock()\fR the subroutine. .SH "STRICT MODE" .IX Header "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 \*(Aqstrict\*(Aq mode: .PP .Vb 1 \& use Test::MockModule qw(strict); .Ve .PP This will disable use of the \f(CWmock()\fR method, making it a fatal runtime error. You should instead define mocks using \f(CWredefine()\fR, which will only mock things that already exist and die if you try to redefine something that doesn\*(Aqt exist. .PP Strictness is lexically scoped, so you can do this in one file: .PP .Vb 1 \& use Test::MockModule qw(strict); \& \& ...\->redefine(...); .Ve .PP and this in another: .PP .Vb 1 \& use Test::MockModule; # the default is nostrict \& \& ...\->mock(...); .Ve .PP You can even mix n match at different places in a single file thus: .PP .Vb 2 \& 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 .Ve .PP NB that strictness must be defined at compile\-time, and set using \f(CW\*(C`use\*(C'\fR. If you think you\*(Aqre going to try and be clever by calling Test::MockModule\*(Aqs \&\f(CWimport()\fR method at runtime then what happens in undefined, with results differing from one version of perl to another. What larks! .SH "GLOBAL STRICT MODE" .IX Header "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 .PP .Vb 1 \& use Test::MockModule \*(Aqglobal\-strict\*(Aq; .Ve .PP 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 \*(Aqnostrict\*(Aq 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. .SH METHODS .IX Header "METHODS" .ie n .IP "new($package[, %options])" 4 .el .IP "new($package[, \f(CW%options\fR])" 4 .IX Item "new($package[, %options])" Returns a singleton\-per\-package mock object. Two calls to \&\f(CW\*(C`Test::MockModule\->new(\*(AqFoo\*(Aq)\*(C'\fR 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 \f(CW\*(C`$mock\->original\*(C'\fR from\-inside\-closure pattern depends on (see GH #83). .Sp Pass \f(CW\*(C`distinct => 1\*(C'\fR 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: .Sp .Vb 4 \& my $m1 = Test::MockModule\->new(\*(AqModule::Name\*(Aq, distinct => 1); \& my $m2 = Test::MockModule\->new(\*(AqModule::Name\*(Aq, distinct => 1); \& # $m1 and $m2 are independent. Tests that need this layering must \& # opt in explicitly. .Ve .Sp Under \f(CW\*(C`distinct\*(C'\fR mode the most recent \f(CW\*(C`mock\*(C'\fR/\f(CW\*(C`redefine\*(C'\fR 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. .Sp If there is no \f(CW$VERSION\fR defined in \f(CW$package\fR, the module will be automatically loaded. You can override this behaviour by setting the \&\f(CW\*(C`no_auto\*(C'\fR option: .Sp .Vb 1 \& my $mock = Test::MockModule\->new(\*(AqModule::Name\*(Aq, no_auto => 1); .Ve .Sp \&\fBGH #83 caveat for distinct mode\fR: a closure that captures \f(CW$mock\fR (typically by calling \f(CW\*(C`$mock\->original(...)\*(C'\fR inside the mock body) prevents \f(CW\*(C`DESTROY\*(C'\fR from firing when \f(CW$mock\fR 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 \&\f(CWnew()\fR calls. Under \f(CW\*(C`distinct => 1\*(C'\fR, prefer the class\-method form \f(CW\*(C`Test::MockModule\->original_for($pkg, $sub)\*(C'\fR from inside closures so they capture only strings, or capture \&\f(CW\*(C`$mock\->original(...)\*(C'\fR in a lexical \fBbefore\fR calling \f(CWmock()\fR. .IP \fBget_package()\fR 4 .IX Item "get_package()" Returns the target package name for the mocked subroutines .IP is_mocked($subroutine) 4 .IX Item "is_mocked($subroutine)" Returns a boolean value indicating whether or not the subroutine is currently mocked .IP \fBmocked_subs()\fR 4 .IX Item "mocked_subs()" Returns a sorted list of the subroutine names that are currently mocked for this module. Useful for debugging complex test setups. .Sp .Vb 4 \& my $mock = Test::MockModule\->new(\*(AqModule::Name\*(Aq); \& $mock\->mock(\*(Aqfoo\*(Aq, sub { 1 }); \& $mock\->mock(\*(Aqbar\*(Aq, sub { 2 }); \& my @mocked = $mock\->mocked_subs; # (\*(Aqbar\*(Aq, \*(Aqfoo\*(Aq) .Ve .IP "mock($subroutine => \e&coderef)" 4 .IX Item "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. .Sp Returns the current \f(CW\*(C`Test::MockModule\*(C'\fR object, so you can chain new with mock. .Sp .Vb 1 \& my $mock = Test::MockModule\->new(...)\->mock(...); .Ve .Sp The following statements are equivalent: .Sp .Vb 2 \& $module\->mock(purge => \*(Aqpurged\*(Aq); \& $module\->mock(purge => sub { return \*(Aqpurged\*(Aq}); .Ve .Sp When dealing with references, things behave slightly differently. The following statements are \fBNOT\fR equivalent: .Sp .Vb 4 \& # 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()]}); .Ve .Sp The following statements are in fact equivalent: .Sp .Vb 3 \& my $array_ref = [localtime()] \& $module\->mock(updated => $array_ref) \& $module\->mock(updated => sub { return $array_ref }); .Ve .Sp However, \f(CW\*(C`undef\*(C'\fR is a special case. If you mock a subroutine with \f(CW\*(C`undef\*(C'\fR it will install an empty subroutine .Sp .Vb 2 \& $module\->mock(purge => undef); \& $module\->mock(purge => sub { }); .Ve .Sp rather than a subroutine that returns \f(CW\*(C`undef\*(C'\fR: .Sp .Vb 1 \& $module\->mock(purge => sub { undef }); .Ve .Sp You can call \f(CWmock()\fR for the same subroutine many times, but when you call \&\f(CWunmock()\fR, the original subroutine is restored (not the last mocked instance). .Sp \&\fBMOCKING + EXPORT\fR .Sp 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: .Sp .Vb 3 \& 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 .Ve .Sp If you are trying to mock a subroutine that was exported into a module that you\*(Aqre trying to test, rather than mocking the subroutine in its originating module, you can instead mock it in the module you are testing: .Sp .Vb 2 \& 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 .Ve .IP redefine($subroutine) 4 .IX Item "redefine($subroutine)" The same behavior as \f(CWmock()\fR, but this will preemptively check to be sure that all passed subroutines actually exist. This is useful to ensure that if a mocked module\*(Aqs interface changes the test doesn\*(Aqt just keep on testing a code path that no longer behaves consistently with the mocked behavior. .Sp Note that redefine is also now checking if one of the parent provides the sub and will not die if it\*(Aqs available in the chain. .Sp Returns the current \f(CW\*(C`Test::MockModule\*(C'\fR object, so you can chain new with redefine. .Sp .Vb 1 \& my $mock = Test::MockModule\->new(...)\->redefine(...); .Ve .IP define($subroutine) 4 .IX Item "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. .Sp By using define, you\*(Aqre asserting that the subroutine you want to be mocked should not exist in advance. .Sp Note: define does not check for inheritance like redefine. .Sp Returns the current \f(CW\*(C`Test::MockModule\*(C'\fR object, so you can chain new with define. .Sp .Vb 1 \& my $mock = Test::MockModule\->new(...)\->define(...); .Ve .IP original($subroutine) 4 .IX Item "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 \f(CWoriginal()\fR before or after mocking. .Sp 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. .Sp .Vb 1 \& 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, @_); \& } \& }); .Ve .ie n .IP "original_for($package, $subroutine)" 4 .el .IP "original_for($package, \f(CW$subroutine\fR)" 4 .IX Item "original_for($package, $subroutine)" Class\-method counterpart to \f(CWoriginal()\fR. Returns the truly\-original coderef for \f(CW\*(C`$package::$subroutine\*(C'\fR from the per\-package registry, or the live sub via the symbol table if not currently mocked. Returns \&\f(CW\*(C`undef\*(C'\fR if no sub by that name exists. Croaks on invalid package or sub names. .Sp The motivating use case is letting closures reach the original sub without capturing \f(CW$mock\fR \-\- the closure\-capture pattern that drives the GH #83 leak under \f(CW\*(C`distinct => 1\*(C'\fR mode: .Sp .Vb 6 \& my $mock = Test::MockModule\->new(\*(AqMyModule\*(Aq, distinct => 1); \& $mock\->mock(\*(Aqgreet\*(Aq, sub { \& # Closure captures only strings \-\- $mock can be GC\*(Aqd at scope end \& return Test::MockModule \& \->original_for(\*(AqMyModule\*(Aq, \*(Aqgreet\*(Aq)\->(@_) . \*(Aq_suffix\*(Aq; \& }); .Ve .Sp For stacked mocks, returns the truly\-original (pre\-any\-mock) coderef, not the layer below. .IP "unmock($subroutine [, ...])" 4 .IX Item "unmock($subroutine [, ...])" Restores the original \f(CW$subroutine\fR. You can specify a list of subroutines to \&\f(CWunmock()\fR in one go. .IP \fBunmock_all()\fR 4 .IX Item "unmock_all()" Restores all the subroutines in the package that were mocked. This is automatically called when all \f(CW\*(C`Test::MockModule\*(C'\fR objects for the given package go out of scope. .IP "noop($subroutine [, ...])" 4 .IX Item "noop($subroutine [, ...])" Given a list of subroutine names, mocks each of them with a no\-op subroutine that returns \f(CW1\fR. Handy for mocking methods you want to ignore! .Sp The \f(CW1\fR return value is part of the public contract of this method (see GH #81) \&\-\- callers in the wild rely on it being truthy. .Sp .Vb 2 \& # Neuter a list of methods in one go \& $module\->noop(\*(Aqpurge\*(Aq, \*(Aqupdated\*(Aq); .Ve .IP mock_all(%options) 4 .IX Item "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. .Sp .Vb 3 \& my $module = Test::MockModule\->new(\*(AqFoo\*(Aq); \& $module\->mock_all(); \& Foo\->bar(); # dies: "Foo::bar was not mocked" .Ve .Sp The \f(CW\*(C`import\*(C'\fR subroutine is always skipped. .Sp Options: .RS 4 .IP "noop => 1" 4 .IX Item "noop => 1" Mock all subroutines with a no\-op sub that returns \f(CW1\fR instead of dying. This is consistent with \f(CWnoop()\fR. .Sp .Vb 2 \& $module\->mock_all(noop => 1); \& Foo\->bar(); # returns 1 .Ve .IP "handler => \e&coderef" 4 .IX Item "handler => &coderef" Provide a custom handler for all mocked subroutines. .Sp .Vb 1 \& $module\->mock_all(handler => sub { warn "unexpected call" }); .Ve .RE .RS 4 .Sp Returns the current \f(CW\*(C`Test::MockModule\*(C'\fR object for chaining. .RE .IP TRACE 4 .IX Item "TRACE" A stub for Log::Trace .IP DUMP 4 .IX Item "DUMP" A stub for Log::Trace .SH "MOOSE AND MOUSE SUPPORT" .IX Header "MOOSE AND MOUSE SUPPORT" When the target package\*(Aqs metaclass is a \f(CW\*(C`Class::MOP::Class\*(C'\fR (Moose) or \&\f(CW\*(C`Mouse::Meta::Class\*(C'\fR (Mouse), \f(CW\*(C`Test::MockModule\*(C'\fR registers mocks with the meta\-object via \f(CW\*(C`add_method\*(C'\fR in addition to installing them in the symbol table. This makes mocked methods visible to: .IP \(bu 4 Moose role \f(CW\*(C`requires\*(C'\fR checks (including dynamic role application via "apply_all_roles" in Moose::Util). .IP \(bu 4 Method modifier resolution (\f(CW\*(C`around\*(C'\fR, \f(CW\*(C`before\*(C'\fR, \f(CW\*(C`after\*(C'\fR) on subclasses loaded after the mock is installed. .IP \(bu 4 Other MOP\-driven introspection that walks \f(CW\*(C`get_method\*(C'\fR / \&\f(CW\*(C`get_method_list\*(C'\fR. .PP \&\f(CW\*(C`unmock\*(C'\fR reverses the registration: if the original method existed on the class itself, it is restored via \f(CW\*(C`add_method\*(C'\fR; if the method was inherited (or absent) before mocking, it is removed via \&\f(CW\*(C`remove_method\*(C'\fR so inheritance lookup falls back to the parent. For Mouse classes (which lack a public \f(CW\*(C`remove_method\*(C'\fR on \&\f(CW\*(C`Mouse::Meta::Class\*(C'\fR), the mock entry is purged from the meta\-class\*(Aqs internal method cache directly to achieve the same effect. .PP If the target class is immutable (\f(CW\*(C`$meta\->is_immutable\*(C'\fR is true), \&\f(CW\*(C`Test::MockModule\*(C'\fR falls back to symbol\-table\-only behavior and emits a warning. Call \f(CW\*(C`Pkg\->meta\->make_mutable\*(C'\fR before mocking if you need MOP\-aware behavior on an immutable class. .SS "Moo and other MOP\-less object systems" .IX Subsection "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 \f(CW\*(C`no_auto => 1\*(C'\fR and explicit load ordering, or convert the affected class to Moose. .SH "SEE ALSO" .IX Header "SEE ALSO" Test::MockObject::Extends .PP Sub::Override .SH AUTHORS .IX Header "AUTHORS" Current Maintainer: Geoff Franks .PP Original Author: Simon Flack .PP Lexical scoping of strictness: David Cantrell .SH COPYRIGHT .IX Header "COPYRIGHT" Copyright 2004 Simon Flack . All rights reserved .PP You may distribute under the terms of either the GNU General Public License or the Artistic License, as specified in the Perl README file.