I am trying to design a class in perl. I am using Mooose. I am using an outside module (let's name it PITA::Parser.
has _parser => (
is => 'ro',
isa => 'object',
builder => _create_parser_object);
#other members here
sub _create_parser_object {
#simplified code
return PITA::Parser->new();
}
sub BUILD {
my $self = shift;
$self->_values($self->load_and_validate_data());
}
sub _load_and_validate_data {
my $values_href;
foreach $key (@key_names) {
$values_href->{$key} = $self->_parser->get_value();
#code to validate the values
return $values_href;
}
I want to mock out the PITA::Parser object. This object looks for a specific file (during new) that is not in my test folder, but rather in the environment where my code will be deployed. So, I am trying to mock it out as such:
my $mock_parser = Test::MockObject->new();
$mock_parser->mock('new', sub {});
$mock_parser->mock('get_value', sub {});
Then I want to create an object of my class
my $my_class_object(_parser => $mock_parser);
However, this does not work, I get an error that get_value can not be located by Test::MockObject.
You can use Test::MockObject to mock the parser object and pass it when creating your own object.
my $mock = Test::MockObject->new();
$mock->mock( 'frobnicate',
sub { return 'file that is not part of test environment' } );
my $obj = Your::Class->new(parser => $mock);
ok( $obj->load_and_validate_data );
It will create an object that has a method frobnicate
. When called in your load_and_validate_data
, it will return the controlled values you want it to return. There's a bunch of other stuff you can do with it. I suggest you take a look at the documentation.