如何测试 Moose 子类型错误消息?

How do I test Moose subtype error messages?

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

模块源(为 whosebug.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';

在 Whosebug 上 post 之前,请先 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';