我想单元测试我的Perl程序,该程序正在使用Backticks。有没有办法嘲笑背部,以便他们做与执行外部命令不同的事情?

另一个问题显示了我需要什么, ,但在红宝石中。不幸的是,我不能选择将Ruby用于此项目,也不想避免回避。

有帮助吗?

解决方案

你可以* 模拟内置 readpipe 功能。 Perl会遇到Backticks或 qx 表达。

BEGIN {
  *CORE::GLOBAL::readpipe = \&mock_readpipe
};

sub mock_readpipe {
  wantarray ? ("foo\n") : "foo\n";
}

print readpipe("ls -R");
print `ls -R`;
print qx(ls -R);


$ perl mock-readpipe.pl
foo
foo
foo

* - 如果你有 Perl版本5.8.9 或以后。

其他提示

您可以使用Backticks,而是可以使用 captureIPC :: System ::简单, ,然后在单元测试中编写捕获()的模拟版本。

# application
use IPC::System::Simple qw(capture);
my $stuff = capture("some command");

# test script
{
     package IPC::System::Simple;
     sub capture
     {
         # do something else; perhaps a call to ok()
     }
}

# ... rest of unit test here
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top