Perl 我们如何使用Test2::V0测试可选的散列字段
我正在尝试解决如何使用来测试可选的散列字段。我目前有以下情况:Perl 我们如何使用Test2::V0测试可选的散列字段,perl,testing,Perl,Testing,我正在尝试解决如何使用来测试可选的散列字段。我目前有以下情况: use 5.016; use Test2::V0; subtest 'optional fields in a hash' => sub { my $check = hash { field foo => qr/^[0-9]+$/; field bar => qr/^[a-zA-Z]+$/; # this field is optional }; like
use 5.016;
use Test2::V0;
subtest 'optional fields in a hash' => sub {
my $check = hash {
field foo => qr/^[0-9]+$/;
field bar => qr/^[a-zA-Z]+$/; # this field is optional
};
like(
{ foo => 1 },
$check,
'should pass when optional field is omitted',
);
like(
{ foo => 2, bar => 'a' },
$check,
'should pass when optional field is provided',
);
};
done_testing;
现在,如果我放弃对可选字段的检查:
my $check = hash {
field foo => qr/^[0-9]+$/;
# field bar => qr/^[a-zA-Z]+$/; # this field is optional
};
考试会通过的。但我想在它存在时测试它的值
有什么想法吗?请参阅集合中的——以下内容适合我。也不要忘记测试失败:-)
我是Test2的发明者/维护者,我认为这个答案是正确的。
use warnings;
use 5.016;
use Test2::V0;
subtest 'optional fields in a hash' => sub {
my $check = hash {
field foo => qr/^[0-9]+$/;
field bar => in_set( DNE(), qr/^[a-zA-Z]+$/ );
};
like( { foo => 1 }, $check,
'should pass when optional field is omitted' );
like( { foo => 2, bar => 'a' }, $check,
'should pass when optional field is provided' );
unlike( { foo => 2, bar => undef }, $check,
'should fail when optional field is provided with no value' );
unlike( { foo => 2, bar => '+' }, $check,
'should fail when optional field is provided with bad value' );
};
done_testing;