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.)


In reply to Re: Testing -- making a new constructor behave differently for one package by tobyink
in thread Testing -- making a new constructor behave differently for one package by tj_thompson

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.