在perl测试中计划死亡

ajw*_*ood 5 testing perl unit-testing

有没有办法为你期望死的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") );
}
Run Code Online (Sandbox Code Playgroud)

zou*_*oul 6

请参阅Test :: Exception:

use Test::Exception;
dies_ok { $foo->method } 'expecting to die';
Run Code Online (Sandbox Code Playgroud)

  • 我发现[Test :: Fatal](http://search.cpan.org/perldoc?Test%3a%3aFatal)比Test :: Exception更容易使用,正如我在[我对前一个问题的回答中所说]同一主题](http://stackoverflow.com/a/4522172/8355). (2认同)

mob*_*mob 5

您将测试包装在一个eval { ... }块中并检查是否$@已设置.

eval { test_thats_supposed_to_fail() };
ok( $@ , "test failed like it was supposed to" );
Run Code Online (Sandbox Code Playgroud)