【发布时间】:2018-09-04 13:10:46
【问题描述】:
我需要为我的模拟框架 Test::Mockify 动态替换带有匿名子的函数。内部我使用了 Sub::Override。 但是我在这里遇到了我喜欢模拟的函数原型的问题。由于警告(原型不匹配:sub ($;$) vs none),我认识到了这个问题。 为了显示问题,我在普通 perl 中复制了没有此框架的问题。
我的示例包带有一个带有原型的函数:
package Hello;
sub FunctionWithPrototype($;$){
my ($Mandatory, $Optional) = @_;
return "original. m:$Mandatory. o:$Optional";
}
1;
我的示例测试:
use Hello;
sub test {
no warnings 'redefine';
# no warnings 'prototype'; # This would hide the problem
is(Hello::FunctionWithPrototype('mand', 'opt'), 'original. m:mand. o:opt' ,'prove return value before change');
is (prototype('Hello::FunctionWithPrototype'),'$;$', 'Prove prototype output of function');
my $OriginalCode = *Hello::FunctionWithPrototype{CODE};
# warn: Prototype mismatch: sub Hello::FunctionWithPrototype ($;$) vs none
*Hello::FunctionWithPrototype = sub {return 'overriden'};
is(Hello::FunctionWithPrototype('mand', 'opt'), 'overriden','prove the mocked function');
# warn: Prototype mismatch: sub Hello::FunctionWithPrototype: none vs ($;$)
*Hello::FunctionWithPrototype = $OriginalCode; #
is(Hello::FunctionWithPrototype('mand', 'opt'), 'original. m:mand. o:opt' ,'prove return value before change (should be as before)');
}
我可以想到这样的解决方案:
my $proto = prototype('FunctionWithPrototype') ? (prototype('FunctionWithPrototype')):undef;
*t::TestDummies::DummyImportTools::Doubler = sub $proto {};
但这当然不是编译:'Illegal declaration of anonymous subroutine',在 sub 中添加 var 是不可能的
【问题讨论】: