如何在 Perl 中创建单元测试?

How to create a unit test in Perl?

我正在尝试为此错误创建单元测试 post 子例程如下所示。此方法接收错误名称并打印出位于每个错误中的值的消息。这是我的代码:

    use constant {
        # link included as a variable in this example
        ERROR_AED => {
        errorCode => 561,
        message => {"this is an error. "},
        tt => { template => 'disabled'},
        link => 'www.error-fix.com',
        },
};


sub error_post {

    my($error) = @_;
    printf ($error->{ message });    
}

error_post(ERROR_AED);

这是我的方法我很确定我试图验证输入值是错误的,或者更普遍地验证它是传递给 error_post 方法的错误。

#verifying input values 

sub test_error_post {
    ok( defined $error, 'Should have an input value' );  # check that it's a constant
    ok($error->isa(constant) , 'Error should be of type constant');
    ok($error->errorCode), 'Should contain key errorCode');
    ok($error->message), 'Should contain key message'); 
    ok($error->tt), 'Should contain key tt');
    ok($error->wiki_page) 'Should contain key wiki page');      
}

我知道这可能还有很长的路要走。

我没有太多时间,但这里有一些关于我如何编写它们的测试。但是,测试应该存在于它们自己的文件中,具有 *.t 扩展名,并且存在于它们自己的目录中。它们不应与您正在编写的代码内联。

use warnings;
use strict;

use Test::More;

use constant {

    ERROR_AED => {
        errorCode => 561,
        message => "this is an error.\n",
        tt => { template => 'disabled'},
        link => 'www.error-fix.com',
    },
};

my $error = ERROR_AED;

is (ref $error, 'HASH', 'ERROR_AED is a hashref');

is (defined $error->{errorCode}, 1, 'ERROR_AED contains an errorCode key');
is ($error->{errorCode}, 561, 'ERROR_AED errorCode is correct');

is (defined $error->{message}, 1, 'ERROR_AED contains key message');
like ($error->{message}, qr/this is an error/, 'ERROR_AED msg output is ok');

is (defined $error->{tt}, 1, 'ERROR_AED contains key tt');
is (ref $error->{tt}, 'HASH', 'ERROR_AED tt is a hashref');
is (defined $error->{tt}{template}, 1, 'ERROR_AED tt href contains template key');
is ($error->{tt}{template}, 'disabled', 'ERROR_AED tt template is ok');

is (defined $error->{link}, 1, 'ERROR_AED has a link key');
is ($error->{link}, 'www.error-fix.com', 'ERROR_AED link is ok');

done_testing();