Test::Mock::Recorder

In xUnit Test Patterns, Gerard Meszaros introduce the term "Test Double" and he lists various kinds of double: dummy object, fake object, stub, spy, and mock. You can read the summary at Martin Folwer's Bliki.

Last year I wrote own mock library for Perl. We can use Test::MockObject as (Gerard's definition of) mock. But it's hard. So my library provides "record-and-verify" style interface like Mox or Mocha.

However I gave a bad name "Test::Double". It's unfocused. So today I've renamed it to Test::Mock::Recorder.

Example

I wrote a small test for KeyedMutex::Memcached. Test::Mock::Recorder verifies the arguments and the order of invocations.

use strict;
use warnings;
use Test::More;
use Test::Mock::Recorder;

use_ok 'KeyedMutex::Memcached';

my $rec = Test::Mock::Recorder->new;
$rec->expects('add')->with('km:online:123', 1, 30)->returns(0);
$rec->expects('add')->with('km:online:123', 1, 30)->returns(1);
$rec->expects('delete')->with('km:online:123');

$rec->verify_ok(
    sub {
        my $km = KeyedMutex::Memcached->new(
            cache => shift
        );
        $km->lock('online:123');
        $km->release;
    }
);

done_testing;

Test::Mock::Recorder provides a shortcut. If you don't have to test the arguments here, you can write like so:

...
my $rec = Test::Mock::Recorder->new;
$rec->expects(
    add    => 0,
    add    => 1,
    delete => 1,
);

$rec->verify_ok(
...

If you have a comment or a question, please email, blog, fork or tweet to me (@kzys).