http://qs1969.pair.com?node_id=11134014


in reply to How to use a private version of a published module?

Here's an example of mocking any subroutine in any module at any level of depth (using my Mock::Sub distribution).

Order of operation:

script.pl <- A.pm <- B.pm <- REST::Client

So A.pm is our module we're testing with script.pl, B.pm can be someone else module used by our A.pm, and REST::Client is being used by the B.pm module which we have no control over.

A.pm

package A; use lib '.'; use B; sub new { return bless {}, shift; } sub call_b { my ($self) = @_; my $b = B->new; return $b->call_rest_client; } 1;

B.pm:

package B; use REST::Client; sub new { return bless {}, shift; } sub call_rest_client { my ($self) = @_; my $client = REST::Client->new; $client->GET('adfdsaf'); return $client->responseContent; } 1;

script.pl:

use warnings; use strict; use feature 'say'; use lib '.'; use A; use Mock::Sub; my $obj = A->new; say "Before mocking REST::Client->responseContent:\n"; say $obj->call_b; # Mock the sub, and set a custom return value my $response_client_sub = Mock::Sub->new->mock('REST::Client::response +Content'); $response_client_sub->return_value('{"a": 1, "b": 2}'); say "After mocking REST::Client->responseContent:\n"; say $obj->call_b;

Output:

Before mocking REST::Client->responseContent: Can't connect to adfdsaf:80 (Name or service not known) Name or service not known at /home/spek/perl5/perlbrew/perls/perl-5.26 +.1/lib/site_perl/5.26.1/LWP/Protocol/http.pm line 50. After mocking REST::Client->responseContent: {"a": 1, "b": 2}

See the documentation for Mock::Sub for full details and usages.