简体   繁体   English

如何在Perl中的对象上模拟-f?

[英]How can I mock -f on an object in Perl?

I have a Perl object that has defined use overload '""' => \\&name; 我有一个Perl对象,该对象已定义了use overload '""' => \\&name; and a name method. name方法。

In my unit tests I have mocked this object, including the name method, but code like 在单元测试中,我模拟了此对象,包括name方法,但代码类似

if (-d $object)

still gives me Use of uninitialized value in -d ... . 仍然给我Use of uninitialized value in -d ... The mocked method is not being executed. 模拟方法未执行。

My mock code: 我的模拟代码:

my $CMmock = Test::MockObject::Extends->new('MyClass');
$CMmock->mock('name', sub { print "TEST!\n";});      
$CMmock->mock('""', sub {print "TEST!\n";});

Other methods that I have mocked are working. 我嘲笑的其他方法正在工作。

[Overly complicated answer involving string evals elided.] [避免了涉及字符串评估的过于复杂的答案。]

overload keeps an idea of what overloads are in effect in a magic place. overload使人知道在魔术位置有效的超载是什么。 Sometimes, especially with dynamically-generated classes, it fails to notice a change. 有时,尤其是对于动态生成的类,它无法注意到更改。 You can force it to pay attention by blessing a fresh object into the class. 您可以通过在班上祝福一个新鲜的物体来强迫它注意。 You can immediately discard the object; 您可以立即丢弃该对象; the blessing event is what matters. 祝福事件才是最重要的。 You don't even have to store the object anywhere. 您甚至不必将对象存储在任何地方。 The following works for me: 以下对我有用:

use Scalar::Util qw(blessed);

my $o = Test::MockObject::Extends->new('MyClass')
        ->mock(name => sub { "Bah!" })
;
bless {} => blessed $o;

print "$o\n";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM