2012-06-04 50 views
5

有沒有一種方法可以爲您希望死亡的Perl調用編寫測試?我想驗證某些調用會因格式不正確的輸入而死掉。perl測試中的死亡計劃

sub routine_a { 
    my $arg = shift; 
    die if $arg eq 'FOO'; 
    print "routine_a: $arg\n"; 
} 
sub routine_b { 
    my $arg = shift; 
    die if $arg eq 'BAR'; 
    print "routine_b: $arg\n"; 
} 

sub test_all { 
    assert(routine_a("blah")); 
    assert(routine_b("blab")); 
    assert_death(routine_a("FOO")); 
    assert_death(routine_b("BAR")); 
} 

回答

6

Test::Exception

use Test::Exception; 
dies_ok { $foo->method } 'expecting to die'; 
+2

我找到[測試::致命](http://search.cpan.org/perldoc?Test%3a%3aFatal)更容易比測試::異常使用,因爲我說[我回答關於同一主題的早期問題](http://stackoverflow.com/a/4522172/8355)。 – cjm

5

您纏繞試驗在eval { ... }塊,並檢查是否[email protected]設置。

eval { test_thats_supposed_to_fail() }; 
ok([email protected] , "test failed like it was supposed to"); 
+0

最好你的測試應該與預期的消息一起死掉,這樣你就可以檢查$ @的值而不是僅僅測試它的存在。 –