views:

105

answers:

2

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.

+2  A: 

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
Ether
If you are going to call a subroutine, just write your own wrapper so you don't have to mock at all.
brian d foy
+10  A: 
mobrule
This seems to only work right in later perls. 5.8.8 only prints foo for `readpipe(...)` and not backticks or `qx`. Works as shown in 5.10.1
Eric Strom
Good catch Eric. This was changed in 5.8.9: http://search.cpan.org/~jesse/perl-5.12.2/pod/perl589delta.pod#readpipe_is_now_overridable
mobrule