【问题标题】:How do I test Moose subtype error messages?如何测试 Moose 子类型错误消息?
【发布时间】:2016-04-06 04:12:51
【问题描述】:

我对属性使用 Moose 子类型,并希望测试(Test::More)它们对违反约束的输入的正确处理。目前 Mooses 的内部错误处理使我的测试文件在看到无效数据时完全停止。

模块源(stackoverflow.com 最小化):

package Doctor;
use Moose;
use Moose::Util::TypeConstraints;
subtype 'Phone_nr_t'
   => as 'Str'
   => where { $_ =~ /^\+?[0-9 ]+$/ }
   => message { 'A Phone_nr must be blabla' };
has 'fax' => (is => 'rw', isa => 'Phone_nr_t');

测试来源:

use Test::More tests=>1;
use Doctor;

my $testdoc=Doctor->new(fax=>'0341 2345678');
throws_ok { $testdoc->fax('123,456') }
    qr('A Phone_nr must be blabla'),
    'fax shall reject bad numbers';

【问题讨论】:

  • 欢迎来到 Stack Overflow 和 Perl 标签。这是一个非常好的第一个问题!我期待更多。 :)

标签: perl unit-testing moose subtype test-more


【解决方案1】:

在您在 StackOverflow 上发帖之前,请use strict。你没有包含use Test::Exception;,所以你没有throws_ok。如果你包括你的代码几乎可以工作。

这行得通:

throws_ok { $testdoc->fax('123,456') }
    Moose::Exception::ValidationFailedForInlineTypeConstraint,
    'fax shall reject bad numbers';

您对正则表达式模式的定义也是错误的。它会尝试匹配不存在的引号。

throws_ok { $testdoc->fax('123,456') }
    qr(A Phone_nr must be blabla),
    'fax shall reject bad numbers';

【讨论】:

  • 其实{}qr 部分不是问题所在。表达式内的单引号是。 qr(foo)qr'foo' 都可以,qr/foo/ 也可以。
  • 我在我的 PC 上有 use strict(我总是使用模板等等),只是在这里将其最小化(然后 Moose::Exception::vali... 也需要引号)。缺少 Test::Exception 因为我编译了一个更新的 perl 来使用 Marpa。现在一切都很好,两个答案都有效。
猜你喜欢
  • 1970-01-01
  • 2015-01-08
  • 2014-10-06
  • 2020-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-22
  • 2019-07-08
相关资源
最近更新 更多