ErrorLibrary.pm:
package Artopi::Builder::ErrorLibrary;
use strict;
use warnings;
use constant {
# wiki link included as a variable in this example
CABLING_ERROR => {
errorCode => 561,
message => "cabling is not correct\n\n ",
t => { template => 'disabled'},
page =>'http://w.error-sol.com/index/Builder/ErrorCodes/_CABLING_ERROR',
},
};
这是我要测试的error_post方法。我正在尝试进行单元测试,以便预期的输出是正确的。我当前的测试无法正确编译,我看不到代码的主要错误。这可能是我应该能够看到/知道的东西。
ErrorPost.pm:
package Artopi::Builder::ErrorPost;
use strict;
use warnings;
use Artopi::Builder::ErrorLibrary;
# takes error name as a param and prints out the message contained in the error hash.
sub error_post {
my($error) = @_;
print ($error->{ message });
}
1;
以下是我提出的当前测试。但这给我一个错误,说:“/ErrorPost.pm第12行使用“strict refs”时,不能将字符串Artopi::Builder::ErrorPost用作HASH ref
error_post.t :
my $error = Artopi::Builder::ErrorLibrary->CABLING_ERROR;
# expected values
my $exp_output = ($error->{message});
my $exp_input = Artopi::Builder::ErrorLibrary->CABLING_ERROR;
# input value as a parameter of error_post method
my $error_in = Artropi::Builder::ErrorPost->error_post($exp_input);
# checking that exp_input matches the expected output after the output has
# been passed through the error_post method
is($error_in, qr/$exp_output/, 'This is the correct output');
有什么建议? :)
最佳答案
您可以使用Test::Output测试打印的内容。
use Test::More;
use Test::Output;
sub error_post {
my ($error) = @_;
print( $error->{message} );
}
stdout_is { error_post( { message => 'foo' } ) } "foo",
'the error message is correct';
# equivalent without the bare block/map-ish syntax
stdout_is(
sub { error_post( { message => 'foo' } ) },
"foo",
'the error message is correct'
);
# and using like
stdout_like { error_post($error) } qr/foo/,
'the error message looks correct';
done_testing;
在这种情况下,根本不会测试您的子返回值。如果两者都需要,则必须将其保存在匿名子目录中,然后再进行测试。
my $rv;
stdout_is { $rv = error_post( { message => 'foo' } ) } "foo",
'the error message is correct';
is $rv, 'expected', '... and the return value is too';
Test::Output在幕后使用Capture::Tiny,如果您只需要使用不受控制的代码来输出,这很好。
关于perl - 如何在Perl中为简单的I/O子例程创建单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36040282/