31 / 32 lines covered (96.9%)
1unit module BDD::Behave::Mock::Allow;23use BDD::Behave::Mock::Double;4use BDD::Behave::Mock::Stub;56class ReceiveSetup is export {7 has Stub $.stub is required;89 method and-return(Mu $value is raw) {10 $!stub.and-return($value);11 self;12 }1314 method and-raise(Mu $exception is raw) {15 $!stub.and-raise($exception);16 self;17 }1819 method and-call-original {20 $!stub.and-call-original;21 self;22 }2324 method and-do(&callable) {25 $!stub.and-do(&callable);26 self;27 }28}2930class AllowBuilder is export {31 has Mu $.target;3233 submethod BUILD(Mu :$target is raw) { $!target := $target }3435 method to { self }3637 method receive(Str:D $method-name) {38 self.validate($method-name);39 if my $existing = StubRegistry.find-existing($!target, $method-name) {40 StubRegistry.remove($existing);41 }42 my $stub = Stub.new(:target($!target), :$method-name);43 $stub.install;44 StubRegistry.register($stub);45 ReceiveSetup.new(:$stub);46 }4748 method validate(Str:D $method-name) {49 my $target := $!target;5051 if $target.WHAT === Double {52 my $cls := $target.double-class;53 if $cls !=== Mu {54 unless $cls.^can($method-name) {55 die "allow(): {$cls.^name} has no method '$method-name'";56 }57 }58 return;59 }6061 my $owner = ($target.defined && $target.DEFINITE) ?? $target.WHAT !! $target;62 unless $owner.^can($method-name) {63 die "allow(): {$owner.^name} has no method '$method-name'";64 }65 }66}6768our sub allow(Mu \target) is export {69 AllowBuilder.new(:target(target));70}7172our sub allow-any-instance-of(Mu \cls) is export {73 if cls.defined && cls.DEFINITE {74 die "allow-any-instance-of(): expected a type object (class), got an instance of {cls.^name}";75 }76 AllowBuilder.new(:target(cls));77}