Simple symbol overriding for tests
When testing a subroutine, it might interact with another subroutine. A useful trick is "mocking", which is to provide a given answer back from that subroutine, helping you imitate some situation for your subroutine to run into, and for you to test.
There's a very easy way to do this:
{
no warnings qw/redefine once/;
*My::Object::connect = sub {
ok( 1, 'Reached connect' );
isa_ok( $_[0], 'My::Object' );
is_deeply( $_[1], { something => 'else' }, 'connect method params' );
};
}
This is a very simple and relatively controlled way to override the subroutine in the symbol table. It is usually what I use.
If you prefer not to play around with the symbol table yourself and leave it to the professional, there's always chromatic with his excellent Test::MockObject which is great for this particular purpose and both you and I should be using it. :)
I'll probably switch over back to it sometime.
Update: whoops, forget the "local". :)
You don't need local?
Nope. :)
just wrote up a similar mocking strategy I use frequently, thanks for the tip
Another blog to follow, thanks! :)
The way you do it is nice. I reckon I never override that many at once in my tests, but I might in the future.