最近,使用MooseX::Declare,我一直在使用“真实对象”作为模拟对象。
假设您有一个执行如下接口的数据库驱动程序:
role Database {
requires 'connect';
requires 'query';
};
然后你有这样的代码使用数据库:
class FooPage {
has 'database' => (
is => 'ro',
does => 'Database',
required => 1,
);
method get_foo() {
$self->database->query({ foo => 42 });
}
method render_page(Str $user) {
"Hello, $user. Here is a foo for you: ". $self->get_foo;
}
};
现在你想测试一下:
use Test::More tests => 2;
use MooseX::Declare;
my $fake_database = class with Database {
has 'data' => ( is => 'ro', isa => 'HashRef' );
has 'connected' => ( is => 'rw', isa => 'Bool' );
method connect() { $self->connected(1) }
method query(HashRef $query) { $self->data->{$query->{foo}} }
};
my $test_database = $fake_database->name->new(
data => {
42 => 'OH HAI',
},
};
my $foo_page = FooPage->new( database => $test_database );
is $foo_page->get_foo, 'OH HAI', 'got correct foo';
is $foo_page->render_page('jrockway'),
'Hello, jrockway. Here is a foo for you: OH HAI',
'got rendered page';
请注意您的语法是如何简洁的,但是作为您的模拟对象的“真实” Moose 类的全部功能。方便,无限灵活。
(这些只是例子......它也可能更好。)