【发布时间】:2010-04-01 18:41:21
【问题描述】:
我目前使用块eval 来测试我已将属性设置为只读。有没有更简单的方法来做到这一点?
工作代码示例:
#Test that sample_for is ready only
eval { $snp_obj->sample_for('t/sample_manifest2.txt');};
like($@, qr/read-only/xms, "'sample_for' is read-only");
更新
感谢 Friedo、Ether 和 Robert P 的回答,感谢 Ether、Robert P 和 jrockway 的 cmets。
我喜欢 Ether 的答案如何通过用 ! 否定它来确保 $is_read_only 只是一个真值或假值(即但绝不是 coderef)。 Double negation 也提供了这一点。因此,您可以在 is() 函数中使用 $is_read_only,而无需打印出 coderef。
有关最完整的答案,请参阅下面 Robert P 的答案。每个人都非常乐于助人,并建立在彼此的答案和 cmets 之上。总的来说,我认为他对我的帮助最大,因此他现在被标记为已接受的答案。再次感谢 Ether、Robert P、frido 和 jrockway。
如果您可能想知道,就像我一开始所做的那样,这里是关于 get_attribute 和 find_attribute_by_name (from Class::MOP::Class) 之间区别的文档:
$metaclass->get_attribute($attribute_name)
This will return a Class::MOP::Attribute for the specified $attribute_name. If the
class does not have the specified attribute, it returns undef.
NOTE that get_attribute does not search superclasses, for that you need to use
find_attribute_by_name.
【问题讨论】:
-
最好写成
ok($snp_obj->meta->get_attribute('sample_for')->get_write_method(), "'sample_for' is read-only");-- 在测试失败时,is()打印第二个参数(这将是一个代码引用).. 更不用说你有第一个和第二个参数颠倒了:is($has, $expected, $test_name). -
如果你的@attribute_names 数组是精心构造的,你应该没问题;但如果该属性不存在,你会爆炸:)
-
+1 用于注意如何在超类中定位属性
标签: perl testing tdd attributes moose