tj_thompson has asked for the wisdom of the Perl Monks concerning the following question:

Hello monks. I have a rather simple question regarding testing and roles. After my reference books and Google have failed me I come to you expert types :)

Assume I have an object $object that I'm playing with in one manner or another. I want to be able to fake that it implements some role such that $object->does('Some::Role') returns true for testing purposes. What is the best way to accomplish this?

EDIT: fixed a grammar typo

Replies are listed 'Best First'.
Re: Testing with Roles
by chromatic (Archbishop) on Dec 17, 2011 at 03:52 UTC

    What does this role do such that you want to fake it? In my experience, roles rarely mean I need to fake things.

    With that said, you can always override DOES() in the class, though if you lie to the type system, you might get weird results.


    Improve your skills with Modern Perl: the free book.

Re: Testing with Roles
by educated_foo (Vicar) on Dec 17, 2011 at 06:57 UTC
    Stripping away the goofy jargon, you want to override the method $obj->does(), i.e. you want to replace the function that gets called. Doing so is no different than replacing any other function:
    *{ref($obj).'::does'} = sub { # do stuff you want }

      This was my original plan but I couldn't seem to get it to work right. That of course was caused by me shooting myself in the foot elsewhere :) Once I resolved the real issue, the problem went away and it passed as expected.

      As always, thank you kind folks for your assistance!

Re: Testing with Roles
by tobyink (Canon) on Dec 17, 2011 at 09:52 UTC

    Maybe something like this?

    $object->meta->add_around_method_modifier(does => sub { my ($orig, $self, $role) = @_; return 1 if $role eq 'Some::Role'; $self->$orig($role); });