MooseX::Test::Role - Test functions for Moose roles
use MooseX::Test::Role; use Test::More tests => 2; requires_ok('MyRole', qw/method1 method2/); my $consumer = consumer_of('MyRole', method1 => sub { 1 }); ok($consumer->myrole_method); is($consumer->method1, 1);
Provides functions for testing Moose roles.
Unit testing a Moose role can be hard. A major problem is creating classes that consume the role.
One could side-step the problem entirely and just call the sub-routines in the role's package directly. For example,
Fooable->bar();
That only works until Fooable calls another method in the consuming class though. Mock objects are a tempting way to solve that problem:
Fooable
my $consumer = Test::MockObject->new(); $consumer->set_always('baz', 1); Fooable::bar($consumer);
But if Fooable::bar happens to call another method in the role then the mock consumer will have to mock that method too.
Fooable::bar
A better way is to create a class to consume the role:
package FooableTest; use Moose; with 'Fooable'; sub required_method {} package main; my $consumer = FooableTest->new(); $consumer->bar();
This can work well for some roles. Unfortunately, if several variations have to be tested, it may be necessary to create several consuming test classes, which gets tedious.
Fortunately, Moose can create anonymous classes which consume roles:
my $consumer = Moose::Meta::Class->create_anon_class( roles => ['Fooable'], methods => { required_method => sub {}, } )->new_object(); $consumer->bar();
This can still be tedious, especially for roles that require lots of methods. MooseX::Test::Role::consumer_of simply makes this easier to do.
MooseX::Test::Role::consumer_of
Creates an instance of a class which consumes the role. Required methods are stubbed, they return undef by default.
To add additional methods to the instance specify the name and coderef:
consumer_of('MyRole', method1 => sub { 'one' }, method2 => sub { 'two' }, required_method => sub { 'required' }, );
Tests if role requires one or more methods.
Patches, comments or mean-spirited code reviews are all welcomed on GitHub:
https://github.com/pboyd/MooseX-Test-Role
Paul Boyd <pboyd@dev3l.net>
This software is copyright (c) 2011 by Paul Boyd.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
To install MooseX::Test::Role, copy and paste the appropriate command in to your terminal.
cpanm
cpanm MooseX::Test::Role
CPAN shell
perl -MCPAN -e shell install MooseX::Test::Role
For more information on module installation, please visit the detailed CPAN module installation guide.