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

j1n*_*3l0 4 testing perl

我正在尝试研究如何使用Test2::V0测试可选的哈希字段。我目前有以下几点:

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;
Run Code Online (Sandbox Code Playgroud)

现在,如果我放弃对可选字段的检查:

my $check = hash {
    field foo => qr/^[0-9]+$/;
    # field bar => qr/^[a-zA-Z]+$/; # this field is optional
};
Run Code Online (Sandbox Code Playgroud)

测试将通过。但我想测试它在那里的价值。

有任何想法吗?

hau*_*kex 5

请参阅Test2::Tools::Compare's in_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;
Run Code Online (Sandbox Code Playgroud)

  • 我是 Test2 的发明者/维护者,我认为这个答案是正确的。 (3认同)