On 4/17/07, Ovid <[EMAIL PROTECTED]> wrote:
Posted at http://www.perlmonks.org/?node_id=610484

So I have some code I'm testing which relies on a class with a whole
bunch of niggling, annoying little methods getting called hither and
yon. For the purposes of my tests, however, I really only care about
one accessor at the end of the test and what it returns (since some
methods are called in void context). I don't care to go through the
trouble of mocking all of the other methods. I'm looking for (and can't
find) a test version of Class::BlackHole. I'm thinking something like
this:

  use Test::Automock;
  my $mock = Test::Automock->('Some::Difficult::Module');
  $mock->add( fetch_my_slippers => sub { 1 } );  # adds this method

  can_ok $object, 'stuff';
  ok $object->stuff, '... and calling it should succeed';

  my @expected = (
    fribble => [ $mock, $object ],
    woobie  => [ $mock ],
  );
  is_deeply $mock->methods_called, [EMAIL PROTECTED],
    "... with Some::Difficult::Methods doing their thing";
  $mock->reset;

Test::Automock would simply use autoload to capture all method calls
and their arguments. Methods by default would return a true value
unless specifically overridden. I'd have to do tricks like overriding
isa() and friends, but that seems like it would be a very lightweight
method of handling mocked objects.

Is there something which does this? Did I miss anything?

Cheers,
Ovid

--

Buy the book -- http://www.oreilly.com/catalog/perlhks/
Perl and CGI -- http://users.easystreet.com/ovid/cgi_course/


Devel::Spy is very similar to this at least in realms of
implementation. It's the instrumentation around your lightweight
object that just returns itself. Here's just a sketch for something
that'd fulfill the other part of your request - an object that just
knows how to return itself. It's an instance of an anonymous class so
you're free to install anything you wish into the class.

Josh

my ( $log, $logger ) = Devel::Spy->make_eventlog;
my $automocked = Devel::Spy->new( Self->new, $logger );
...


package Self;
our $NAMESPACE = 1;
sub create_new {
   # Creates a
   my $pkg = 'Self::GEN' . $NAMESPACE++;
   *{"${pkg}::AUTOLOAD"} = \ &_AUTOLOAD;
   *{"${pkg}::DESTROY"} = \ &_DESTROY;
   return bless [], $pkg;
}
sub _DESTROY {
   # Reap my autogenerated namespace
   my ( $ns ) = ref( $_[0] ) =~ /(\d+)/;
   delete $Self::{"GEN${ns}::};
}
sub _AUTOLOAD { return $_[0] }

Reply via email to