perltest-more

How to pass Arguments when call require_ok '*.pl' to test by Test::More


I'm wondering the way to test each Subroutings in *.pl files individually. But Can't use 'require' clause because some *.pl requires Arguments.

for example

use Test::More;
require "some.pl"

will always fail Test at 'require'.
because "some.pl " required a argument and end with

exit(0);

of the file.

I just want to test "Func1,usage,...whatever," every subroutings in '*.pl' individually.

some.pl is like that

my ( $cmd) = @ARGV;  
if (!defined $cmd ) {
    usage();
} else {
    &Func1;
}
exit(0);

sub Func1 {
      print "hello";
    }

sub usage {
     print "Usage:\n",
    }

How can I write a test code for "sub Func1" by "Test::More"?

Any suggestions appreciate.


Solution

  • To exercise a standalone script that you expect to exit, run it with system. Capture the output and inspect it at the end of the system call.

    use Test::More;
    my $c = system("$^X some.pl arg1 arg2 > file1 2> file2");
    ok($c == 0, 'program exited with successful exit code');
    open my $fh, "<", "file1";
    my $data1 = do { local $/; <$fh> };
    close $fh;
    open $fh, "<", "file2";
    my $data2 = do { local $/; <$fh> };
    close $fh;
    ok( $data1 =~ /Funct1 output/, "program called Funct1");
    ok( $data2 !~ /This is how you use the program, you moron/,
        "usage message not printed to STDERR" );
    unlink("file1","file2");