测试::更多不知道测试是否死亡 - 所以我该如何测试?

fli*_*ies 7 testing perl module

我正在收集一堆子程序,这些子程序对于我的一堆脚本而言是常见的.(我应该已经做了这样较早,但开始了继承的脚本.)我在造型上我的工作非常有帮助的例子在这里,使用测试::更多和模块::编译

从文件读取或写入的所有子例程都包含一行open() or die "errmsg".我正在为模块编写测试并遇到了这个问题.其中一个子程序检查路径是否指向某个东西,在失败时死亡.在继承的脚本中,子例程如下所示:

sub checkExist {
  my ($type, $path) = @_;
  if ($type eq 'd') {
    if (! -d $path) {
      warn("dir not found: $path\n");
      die $pathNotFound;
    }
  }
  elsif ($type eq 'f') {
    if (! -f $path) {
      warn("file not found: $path\n");
      die $pathNotFound;
    }
    elsif (! -s $path) {
      warn("empty file: $path\n");
      die $emptyFile;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,我正在使用以下行测试它:

is(HomeBrew::IO::checkExist('f', $0), '', "can checkExist find file $0 ?");
Run Code Online (Sandbox Code Playgroud)

哪个工作正常,除非我选择一个不存在的路径,在这种情况下测试脚本会死,但测试成功,产生以下输出:

# Looks like your test exited with 2 just after 5.
Dubious, test returned 2 (wstat 512, 0x200)
All 5 subtests passed 
Run Code Online (Sandbox Code Playgroud)

我更喜欢这是一个失败的测试(而不是一个可疑的传递),但由于这是遗留代码,我也希望这个子程序在失败时停止执行.该怎么办?在函数上编写测试这么简单是愚蠢的吗?

我已经编写了一个checkExist2函数,我将来会使用它返回undef成功,否则会出现非零错误(所以我可以die if checkExist2()在别处写).其他建议不保持checkExist的功能是值得欢迎的.

Eth*_*her 16

测试代码是否存在或者是否存在正确错误的正确方法是使用Test :: Exception.您可以围绕其他测试用例包装此测试,因为它只需要一个coderef:

use Test::More;
use Test::Exception;

lives_ok {
    is(HomeBrew::IO::checkExist('f', $0), '',
    "can checkExist find file $0 ?")
} '...and code does not die';
Run Code Online (Sandbox Code Playgroud)