Created
July 9, 2013 01:21
-
-
Save tsucchi/5953898 to your computer and use it in GitHub Desktop.
Test::Stub 使おうかと思ったら、オブジェクトを生成しないと使えないのがつらくて試しにこんなの書いてみたけど、イマイチだなぁ..
This file contains hidden or 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 EasyStub; | |
| use base qw(Exporter); | |
| our @EXPORT_OK = qw(stub); | |
| use strict; | |
| use warnings; | |
| my $id = 0; | |
| sub stub_anon_object { | |
| my (%methods) = @_; | |
| my $class = "EasyStub::Anon_" . $id++; | |
| my $obj = bless {}, $class; | |
| _build_stubbed_methods($class, %methods); | |
| return $obj; | |
| } | |
| sub stub_package { | |
| my ($package_name, %methods) = @_; | |
| my $obj = bless {}, $package_name; | |
| _build_stubbed_methods($package_name, %methods); | |
| return $obj; | |
| } | |
| sub _build_stubbed_methods { | |
| my ($class_name, %methods) = @_; | |
| for my $method_name ( keys %methods ) { | |
| my $code = $methods{$method_name}; | |
| $code = defined ref $code && ref $code eq 'CODE' ? $code : sub { return $methods{$method_name} }; | |
| { | |
| no strict 'refs'; | |
| no warnings 'redefine'; | |
| *{ $class_name . "::" . $method_name } = $code; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment