2010-01-12 18 views
5

我有以下Perl代码:为什么Perl的eval从Test :: Cmd :: Common-> unlink捕获问题?

use strict; 
use warnings; 
use Test::Cmd::Common; 

my $path = "/something/not/available"; 
my $test = Test::Cmd::Common->new(string => 'File system operations'); 

eval{ 
     $test->unlink("$path"); 
}; 
ok([email protected], "file unlike"); 

print "done.\n"; 

的$测试 - >取消链接()线将失败,并抛出异常。但问题是:eval不处理该异常并且代码执行被中断。

输出:

$ perl test.pl 
could not unlink files (/something/not/available): No such file or directory 
NO RESULT for test at line 561 of /home/y/lib/perl5/site_perl/5.8/Test/Cmd/Common.pm (Test::Cmd::Common::unlink) 
    from line 9 of test.pl. 

是EVAL在这里做合适的工作?或者我误解了一些东西?

F.

回答

11

从测试:: Cmd的常见::文档的“删除指定文件退出NO的结果,如果任何文件不能以任何理由被删除。”。并通过查看源,测试:: Cmd的::俗称的Test :: CMD-> no_result,这确实

exit (2); 

“退出”不能被EVAL被困,所以它是预期的行为。

+0

未经检验的,但如何'*测试:: Cmd的:: no_result = {子死'没有结果'}'? – jrockway

1

这是略正交的,但如果你想测试,如果操作“成功”或死亡,使用Test::Exception

use strict; 
use warnings; 
use Test::More tests => 2; 
use Test::Exception; 

note 'File system operations'; 
dies_ok 
    { some_operation_which_may_die(); } 
    'operation died'; 

throws_ok 
    { some_operation_which_may_die(); } 
    /String we expect to see on death/, 
    'operation died with expected message';