Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Perl 我们如何使用Test2::V0测试可选的散列字段_Perl_Testing - Fatal编程技术网

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;