最近,有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';
請注意,您如何使用簡潔的語法,但「真實」的全部功能 麋類作爲你的模擬對象。方便,無限靈活。
(這些僅僅是例子......它也可能是更好的東西。)
Test :: Class是基於對象的測試的絕佳工具;它是輕量級的,可與Test :: More和所有Test :: Builder相關的單元測試工具一起使用。 – 2009-10-05 19:57:56