0

我正在尝试使用 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()总是返回。maround 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, \@_ );
  }
};

有效,但写起来有点冗长和麻烦。

有没有更好的选择来用 Moops 实现这样的目标?

4

1 回答 1

2

就我个人而言,无论是 Moops 还是其他人,我都不相信caller任何可能会对其应用修饰符的方法。我也不会相信那些修饰符。您过于依赖方法修饰符如何工作的内部结构。(这在 Moo/Moose/Mouse 之间会有所不同。)

你有没有尝试过这样的事情?

push @{ $self->methodCallLog }, Sub::Identify::sub_name($next);

(或者使用 Sub::Util 而不是 Sub::Identify。)

于 2015-01-28T23:01:11.703 回答