给定以下角色:
package MyRole;
use Moo::Role;
sub foo {
return 'blah';
}
以及以下消费类:
package MyClass;
use Moo;
with 'MyRole';
around foo = sub {
my ($orig, $self) = @_;
return 'bak' if $self->$orig eq 'baz';
return $self->$orig;
}
我想测试around
修饰符中定义的行为。我该怎么做呢?似乎 Test::MockModule 不起作用:
use MyClass;
use Test::Most;
use Test::MockModule;
my $mock = Test::MockModule->new('MyRole');
$mock->mock('foo' => sub { return 'baz' });
my $obj = MyClass->new;
# Does not work
is $obj->foo, 'bak', 'Foo is what it oughtta be';
编辑:我要测试的是修饰符中定义的 MyClass 与 MyRole的交互。around
我想测试around
修饰符中的代码是否符合我的想法。这是另一个更接近我的实际代码的示例:
package MyRole2
use Moo::Role;
sub call {
my $self = shift;
# Connect to server, retrieve a document
my $document = $self->get_document;
return $document;
}
package MyClass2;
use Moo;
with 'MyRole2';
around call = sub {
my ($orig, $self) = @_;
my $document = $self->$orig;
if (has_error($document)) {
die 'Error';
}
return parse($document);
};
所以我在这里要做的是模拟MyRole2::call
返回一个静态文档,在我的测试夹具中定义,其中包含错误并测试异常是否被正确抛出。我知道如何使用Test::More::throws_ok
或类似方法对其进行测试。我不知道该怎么做是模拟MyRole2::call而不是 MyClass2::call
。