use warnings; use strict; use Test::More; use Test::MockObject; # should be declared before the BEGIN block (see perlmod) my ($mocked_foo, $mocked_bar); # fake_module is in BEGIN to prevent loading of the actual package BEGIN { # create the mocked objects $mocked_foo = Test::MockObject->new(); $mocked_bar = Test::MockObject->new(); # prevent Perl from loading the mocked class $mocked_foo->fake_module('Class::To::Mock::Foo'); $mocked_bar->fake_module('Class::To::Mock::Bar'); # cheat the target code $mocked_foo->set_isa('Class::To::Mock::Foo'); $mocked_bar->set_isa('Class::To::Mock::Bar'); # load the class to test use_ok 'Your::Test::Class'; } # set up the mockery for foo # this scalar will hold the value of the get/get operations # of the fake accessors my $accessor_one_scalar = 'init_value'; $mocked_foo->mock( 'accessor_one', sub {shift; &mock_accessor_scalar(\$accessor_one_scalar,@_)} ); # now mock foo in bar $mocked_bar->mock('foo', sub { return $mocked_foo }); # use the mocked object in your target code my $test_target = Your::Test::Class->new( bar => $mocked_bar, ); # ================== # Actual Tests Here # ================== # use the scalars in your tests for example # suppose your target code does something like: # $self->bar->foo->accessor_one('test_value'); ok($test_target->mess_with_bar_foo, 'Operation on mocked bar that affects foo'); cmp_ok($accessor_one_scalar, 'eq', 'test value', 'Result of operation in foo'); # end of tests done_testing(); # emulates a simple accessor to a scalar sub mock_accessor_scalar { my $var = shift; if(@_){ $$var = shift; } else{ return $$var; } }