in reply to Testing -- making a new constructor behave differently for one package
Given that you're already using Moose, which has method modifiers, don't mess around with rubbish like this:
no warnings 'redefine'; *Foo::real_new = \&Foo::new; *Foo::new = sub { if (caller() eq 'Bar') { print "Returning real Foo.\n"; return Foo->real_new; } print "Returning fake Foo.\n"; return FakeFoo->new; };
Use the features of your framework:
{ package Foo; use Moose; around new => sub { my ($orig, $class, @args) = @_; if (caller() eq 'Bar') { print "Returning real Foo.\n"; return $class->$orig(@args); } print "Returning fake Foo.\n"; return FakeFoo->new(@args); }; }
Be aware that putting method modifiers on new can interfere with class immutability, so avoid doing this in production code. It should work fine for testing though.
(Also be aware that the call stack can have various Moosey things in it when you use method modifiers. So checking caller() might not be enough - you might need to walk up the call stack a little.)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Testing -- making a new constructor behave differently for one package
by tj_thompson (Monk) on Jan 30, 2012 at 18:58 UTC | |
by tobyink (Canon) on Jan 30, 2012 at 22:32 UTC | |
by tj_thompson (Monk) on Jan 31, 2012 at 17:59 UTC |