【发布时间】:2015-07-15 11:53:18
【问题描述】:
我正在尝试使用 Test::More 和 Test::Exception 库为我的脚本创建单元测试。
我已阅读这些文章How to test for exceptions in Perl 和Test::Exception。
第一篇文章准确描述了我需要什么来测试我的子例程是否抛出异常或死机。
但我无法让它工作。考虑一些例子
#!/usr/bin/env perl
package My::SuperModule;
use strict;
use warnings;
use Net::Ping;
use Utils::Variables::Validator;
sub new
{
die "Hello";
#Getting class name from, stored in $_[0]
my $class = shift;
#Getting user name from arguments $_[1]
my $user_name = shift;
........
}
还有我的测试文件
use warnings; # this warns you of bad practices
use strict; # this prevents silly errors
use Test::More; # for the is() and isnt() functions
use Test::Exception;
do './My/SuperModule.pm';
#Testing module loading
print "=================Testing module loading=================\n";
use_ok ( 'My::SuperModule' );
use_ok ( 'My::SuperModule', 'new' );
#Testing module subroutines
dies_ok { My::SuperModule->new() } "Died in class constructor";
sub div {
my ( $a, $b ) = @_;
return $a / $b;
};
dies_ok { div( 1, 0 ) } 'divide by zero detected';
它在任何情况下都会停止执行脚本,但我只需要处理如果死了,我需要对此进行测试,因为如果数据无效或其他情况我手动调用 die ,但它死了并且不会继续执行脚本更远。给我留言
Uncaught exception from user code:
Hello at ../libs/My/SuperModule.pm line 31.
My::SuperModule::new('My::SuperModule', '') called at SuperModule.t line 24
# Tests were run but no plan was declared and done_testing() was not seen.
# Looks like your test exited with 2 just after 8.
但是如果使用除以零,它就像我想要的那样工作
ok 16 - divide by zero detected
所以它失败但不会终止脚本的执行。
我是Perl的新手,所以不能自己解决问题,也许根本没有问题,只是没有办法做我想做的事。
请建议该怎么做或说我的错在哪里。
编辑
我刚刚尝试在我的模块新子例程中除以零,这是我得到的消息。
Illegal division by zero at ../libs/My/SuperModule.pm line 33 (#1)
(F) You tried to divide a number by 0. Either something was wrong in
your logic, or you need to put a conditional in to guard against
meaningless input.
我真的不知道发生了什么。请帮忙。
【问题讨论】:
-
你为什么
do你的模块?说一次use_ok 'My::SuperModule';就够了。其他所有use_ok和do都不需要。
标签: perl unit-testing exception perl-module die