in reply to Mocking IO::Socket::INET

There are two problems:
  1. You return $mock from IO::Socket::INET->new, but that's an object responsible for mocking the class, not an object pretending to be IO:Socket::INET. I'm not familiar with Test::MockObject, but it seems it doesn't provide an easy way to create the mocked object, so you probably have to go low level and create the object yourself:
    new => sub { bless {}, 'IO::Socket::INET' },
  2. The methods of IO::Socket::INET remain mocked only while the $mock object exists. Once you don't return it from the constructor, it goes out of scope at the end of mock_me and IO::Socket::INET will behave in its original way. You need to return the $mock object from there to the test so IO::Socket::INET stays mocked.

This works for me:

#!/usr/bin/perl use warnings; use strict; { package main; use Test::More tests => 2; use Test::Exception; use Test::MockModule; my ($obj, $mock) = mock_me( # Keeping the $mock object. send => sub { $_[0]->{howdy} = 1 if $_[1] eq 'Howdy!' }, recv => sub { $_[0]->{howdy} ? 'Welcome' : 'Hiya!' }, ); is 'My::Module', ref $obj, 'Correct module'; lives_ok { $obj->connect } 'Connection and handshake success'; sub mock_me { my $mock = Test::MockModule->new('IO::Socket::INET'); my %mock = ( # Initializing the object. new => sub { bless {}, 'IO::Socket::INET' }, @_ ); $mock->mock($_ => $mock{$_}) for keys %mock; return My::Module->new, $mock # Returning the $mock object. } } { package My::Module; use Carp; use IO::Socket 1.18; sub new { my $class = shift; bless { }, $class } sub connect { my $s = shift; $s->{socket} = IO::Socket::INET->new( PeerAddr => '127.0.0.1', PeerPort => 8080, Proto => 'tcp', ) or croak "Connection failed: $!"; croak 'Invalid handshake' unless $s->{socket}->recv eq 'Hiya!' +; $s->{socket}->send('Howdy!'); croak 'ACK barf' unless $s->{socket}->recv eq 'Welcome'; 1; } }

map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^2: Mocking IO::Socket::INET
by wanna_code_perl (Friar) on Aug 31, 2019 at 22:00 UTC
    $choroba->eureka;

    That did the trick. Thank you very much.