如何在 Perl 中为简单的 I/O 子例程创建单元测试

How to create a unit test for a simple I/O subroutine in Perl

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 方法。我正在尝试进行单元测试,以便预期的输出是正确的。我当前的测试无法正确编译,我看不出我的代码有什么主要问题。这可能是我应该能够 see/know.

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;

以下是我提出的当前测试。但它给了我一条错误消息:'Can't use string Artopi::Builder::ErrorPost as a HASH ref while "strict refs" in use at /ErrorPost.pm Line 12

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;

在这种情况下,根本没有测试您的 sub 的 return 值。如果两者都想要,则必须将其保存在匿名子程序中,稍后再进行测试。

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,如果您只需要在您无法控制的代码中进行输出,这非常好 go away.