문제

I'd like to unit test a Perl program of mine that is using backticks. Is there a way to mock the backticks so that they would do something different from executing the external command?

Another question shows what I need, but in Ruby. Unfortunately, I cannot choose to use Ruby for this project, nor do I want to avoid the backticks.

도움이 되었습니까?

해결책

You can* mock the built-in readpipe function. Perl will call your mock function when it encounters a backticks or qx expression.

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

* - if you have perl version 5.8.9 or later.

다른 팁

Instead of using backticks, you can use capture from IPC::System::Simple, and then write a mock version of capture() in your unit test.

# 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