我正在尝试使用moops构建一个方便的模拟类:
#!/usr/bin/env perl
use Modern::Perl '2014';
use Moops;
use Test::More;
class aClass {
method m {}
method l {}
};
class NotWorkingMockAClass
extends aClass {
has methodCallLog => (
is => 'rw',
default => sub { [] },
isa => ArrayRef
);
around m, l {
push $self->methodCallLog, (caller(0))[3] =~ m/::(\w+)$/;
$next->($self, @_ );
}
};
my $mac = NotWorkingMockAClass->new();
$mac->m();
$mac->l();
$mac->m();
is( ($mac->methodCallLog)->[0], 'm', 'mcl[0] == m' );
is( ($mac->methodCallLog)->[1], 'l', 'mcl[1] == l' );
is( ($mac->methodCallLog)->[2], 'm', 'mcl[2] == m' );这产生了:
$ perl mocking.pl
ok 1 - mcl[0] == m
not ok 2 - mcl[1] == l
# Failed test 'mcl[1] == l'
# at mocking.pl line 33.
# got: 'm'
# expected: 'l'
ok 3 - mcl[2] == m因此,问题似乎是,当我使用caller()快捷方式时,m总是返回around m,l ..。
类的定义如下:
class WorkingMockAClass
extends aClass {
has methodCallLog => (
is => 'rw',
default => sub { [] },
isa => ArrayRef
);
method _logAndDispatch( CodeRef $next, ArrayRef $args ){
push $self->methodCallLog, (caller(1))[3] =~ m/::(\w)$/;
$next->($self, @$args );
}
around m {
$self->_logAndDispatch( $next, \@_ );
}
around l {
$self->_logAndDispatch( $next, \@_ );
}
};可以工作,但是编写起来有点冗长和繁琐。
有更好的选择来实现这样的目标吗?
发布于 2015-01-28 23:01:11
就我个人而言,无论是Moops还是其他方面,我都不相信caller有任何可能会应用修饰符的方法。我也不相信这些修饰语。您太依赖于方法修饰符的内部结构。(Moo/Moose/老鼠之间会有不同。)
你试过这样的东西吗?
push @{ $self->methodCallLog }, Sub::Identify::sub_name($next);(或者使用Sub::Util代替Sub::标识)
https://stackoverflow.com/questions/28173912
复制相似问题