Created
May 10, 2018 15:28
-
-
Save rymizuki/ca027c11db7ad9abbcbca0dc69c335d7 to your computer and use it in GitHub Desktop.
PerlでSinon.jsライクにcalled_countとcalled_argsを呼び出せるなにか
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Test::Spy; | |
use Mouse; | |
use Test::Mock::Guard (); | |
has module => ( | |
is => 'ro', | |
isa => 'ClassName', | |
); | |
has method => ( | |
is => 'ro', | |
isa => 'Str', | |
); | |
has mock_object => ( | |
is => 'ro', | |
isa => 'Object', | |
builder => '_build_mock_object', | |
); | |
has called_count => ( | |
is => 'ro', | |
isa => 'Int', | |
default => 0, | |
); | |
has called_args => ( | |
is => 'ro', | |
isa => 'ArrayRef', | |
default => sub { [] }, | |
); | |
around BUILDARGS => sub { | |
my ($orig, $class, $module, $method) = @_; | |
return $class->$orig( | |
module => $module, | |
method => $method, | |
); | |
}; | |
sub called { | |
my ($self, $args) = @_; | |
$self->{called_count}++; | |
push @{ $self->{called_args} } => $args; | |
} | |
sub _build_mock_object { | |
my $self = shift; | |
my $module = $self->module; | |
my $method = $self->method; | |
my $orig = $self->module->can($self->method) | |
or die "'$method' is not defined in '$module'!!"; | |
my $guard = Test::Mock::Guard::mock_guard($module, +{ | |
$method => sub { | |
my ($context, @args) = @_; | |
$self->called([@args]); | |
warn 'called'; | |
$orig->($context, @args); | |
} | |
}); | |
return $guard; | |
} | |
sub DESTROY { | |
my $self = shift; | |
$self->{mock_object} = undef; | |
} | |
1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment