首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何为Perl中的简单I/O子程序创建单元测试

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

Stack Overflow用户
提问于 2016-03-16 15:35:24
回答 1查看 80关注 0票数 2

ErrorLibrary.pm:

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
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;

下面是我目前提出的测试。但是它给了我一个错误:‘不能使用字符串Artopi::Builder::ErrorPost作为散列参考,而在/ErrorPost.pm第12行使用“严格参考”

代码语言:javascript
运行
复制
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');   

有什么建议吗?)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-16 15:52:58

您可以使用测试::输出测试印刷品。

代码语言:javascript
运行
复制
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;

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

代码语言:javascript
运行
复制
my $rv;
stdout_is { $rv = error_post( { message => 'foo' } ) } "foo", 
  'the error message is correct';
is $rv, 'expected', '... and the return value is too';

测试::output在引擎盖下使用捕捉:微小,如果您只需要使不受控制的代码中的输出消失,这是很棒的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36040282

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档