Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking super class calls in Perl (using Test::MockObject)

I'm using MockObjects in some of my tests and just had to test a function with a call to a SUPER class and I cannot seem to make it work. Can UNIVERSAL calls like $this->SUPER::save() not be mocked? If yes, how do you do it?

Thanks.

Edit:

Found it!

Use fake_module from Test::MockObject

So, let's say your base module it Some::Module, and your subroutine is making a $this->SUPER::save call, use

my $child_class_mockup = Test::MockObject->new();
$child_class_mockup->fake_module(
    'Some::Module',
    save => sub () { return 1; } 
);

Leaving the question open for a couple of days, to get inputs about different ways/libraries of doing this (what if, the SUPER call had a SUPER call?) before accepting this answer.

like image 703
Gaurav Dadhania Avatar asked Feb 25 '11 00:02

Gaurav Dadhania


1 Answers

Find out the name of the object's superclass (or one of the superclasses, since Perl has multiple inheritance), and define the save call in the superclass's package.

For example, if you have

package MyClass;
use YourClass;
our @ISA = qw(YourClass);   # <-- name of superclass
...
sub foo {
    my $self = shift;
    ...
    $self->SUPER::save();    # <--- want to mock this function in the test
    ...
}

sub save {
    # MyClass version of save method
    ...
}

then in your test script, you would say

no warnings 'redefine';     # optional, suppresses warning

sub YourClass::save {
    # mock function for $yourClassObj->save, but also
    # a mock function for $myClassObj->SUPER::save
    ...
}
like image 188
mob Avatar answered Oct 26 '22 22:10

mob