If you're enforcing the object type you have to draft in Test::MockObject, which is great, but is also substantially more complex.

You can still use the self-shunt unit testing pattern with enforced object types and Test::Class if you take advantage of perl's run-time method dispatch.

For example, consider a class that takes an optional logging object to allow custom logging on an object by object basis.

package Object; use Params::Validate qw(:all); sub new { my $class = shift; my %self = validate(@_, {logger => { isa => 'Logger' } } ); return( bless \%self, $class ); }; # ... more code ... sub log { my ($self, @messages) = @_; $self->{logger}->log($self, @messages); };

One way to test Object's log method would be to create a mock Logger object with Test::MockObject and pass this to Object->new. Instead, we will make the Test::Class pretend to be a Logger object.

package Object::Test; use base qw(Test::Class); use Test::More; # run $code while pretending that __PACKAGE__ ISA $class sub _do_as(&$) { my ($code, $class) = @_; { # we have to make sure the package hash exists # for the method dispatch to work no strict 'refs'; *{"$class\::"}{HASH} }; local @Object::Test::ISA = ($class, @Object::Test::ISA); $code->(); }; sub setup : Test(setup) { my $self = shift; _do_as { $self->{object} = Object->new(logger => $self) } 'Logger' +; }; sub test_show_answer : Test(3) { my $self = shift; _do_as { $self->{object}->log("hello", "there") } 'Logger'; }; sub log { my $self = shift; is($_[0], $self->{object}, 'passed object to logger'); is($_[1], "hello", 'passed arg1'); is($_[2], "there", 'passed arg2'); };

Sneaky - eh?


In reply to Test::Class & self-shunt pattern by adrianh
in thread Documenting Methods/Subs by vek

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.