我们如何使用Test2 :: V0测试可选的哈希字段

时间:2019-01-28 18:43:37

标签: perl testing

我正在尝试找出如何使用Test2::V0测试可选哈希字段的方法。我目前有以下内容:

RoundedEntry entry= new RoundedEntry();

现在,如果我取消选中可选字段:

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;

测试将通过。但是我想测试它的值。

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

请参见Test2::Tools::Comparein_set-以下内容对我有用。别忘了还要测试失败:-)

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;