Reputation: 41
I'm trying to mock a call to fork using mockmodule. I'm setting it up like this...
my $mock = Test::MockModule->new('Foo');
$modMock->mock(fork => sub { print "here"; return 0; });
where my module is Foo.pm. I've had experience with other module calls getting loaded into the module under test, and mocking module calls like this seems to work well. However, my mock print statement is never reached (and the real fork is called).
Is this the correct way to mock system calls like fork? Should I be loading a different module than the system under test?
Upvotes: 3
Views: 517
Reputation: 118605
Your code is assigning a subroutine definition to the name &Foo::fork
, and you can always execute it by calling the fully qualified function name Foo::fork()
or by using the sigil &fork
while in the Foo
namespace.
package Foo;
TestModule->new('Foo')->mock(fork => sub { ... });
Foo::fork; # calls mocked function
⋔ # calls mocked function
{ package Bar; &fork } # error: no &Bar::fork
fork; # calls builtin
Overriding a built-in function, so that a call to a bare fork
invokes your function instead of the builtin, "may be done only by importing the name from a module at compile time". If that was hard to grok, just know that the subs
pragma satisfies this condition for you:
package Foo;
use subs 'fork'; # compile-time import of name 'fork'
TestModule->new('Foo')->mock(fork => sub { ... });
Foo::fork; # calls mocked function
⋔ # calls mocked function
fork; # now calls mocked function
{ package Bar; fork; } # calls builtin
CORE::fork; # always calls builtin
Upvotes: 4