我目前使用eval
块来测试我已经将属性设置为只读。有没有更简单的方法来做到这一点?从工作中有没有简单的方法来测试Moose属性是否只读?
例子:
#Test that sample_for is ready only
eval { $snp_obj->sample_for('t/sample_manifest2.txt');};
like([email protected], qr/read-only/xms, "'sample_for' is read-only");
UPDATE
感谢friedo,乙醚和罗伯特·P代表他们的答案和醚,罗伯特·P和jrockway征求意见。
我喜欢甲醚的答案如何确保$is_read_only
仅仅是一个真或假的值(即却从CODEREF)通过用!
否定它。 Double negation也提供。因此,您可以在is()
函数中使用$is_read_only
,而无需打印出coderef。
有关最完整的答案,请参见下面的Robert P的答案。每个人都非常有帮助,并建立在彼此的答案和评论。总体而言,我认为他对我的帮助最大,因此他现在被标记为接受的答案。再次感谢Ether,Robert P,friedo和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()'输出第二个参数(这将是一个coderef )..更不用说你有第一个和第二个参数相反了:'是($ has,$ expected,$ test_name)'。 – Ether 2010-04-01 19:19:56
如果你的@attribute_names数组是精心构造的,你应该没问题;但如果该属性不存在,您将爆炸:) – 2010-04-02 16:55:10
+1注意如何在超类中定位属性 – user1027562 2013-06-27 15:16:59