in reply to Re: perl script testing
in thread perl script testing

Thanks for the solution I think 2nd method which you told is suitable to test my scripts.
I am new for testing and can you please explain what is "# Main routine here" and "... rest of implementation here..." and "__PACKAGE__->run() unless caller();"

you have told to "write tests for the subs in it" what it means?????

Replies are listed 'Best First'.
Re^3: perl script testing
by pemungkah (Priest) on Dec 10, 2013 at 23:00 UTC
    This is a skeleton of your application to be:
    package MyCode; use strict; use warnings; sub run { # Main routine here } ... rest of implementation here... __PACKAGE__->run() unless caller(); 1;
    The "Main program here" section is going to be the code that basically reads the command line options, figures out what to do, and then calls the other subs or methods to make it happen. The "rest of implementation here" is simply placeholder text to indicate where you'd put the code that actually implements getting things done - that is the code your tests would be testing. The "__PACKAGE__..." line is what makes this .pm file into an executable program; it says "if caller() doesn' return anything (that is, we haven't been loaded by someone else as a module), execute this package's run() method."

    Here's a contrived example.

    package Sample; use strict; use warnings; use GetOpt::Long; __PACKAGE__->run() unless caller(); sub run { my($should_foo); die "usage: Sample.pm [--foo|--bar]\n" unless(GetOptions('foo' => \$should_foo, 'bar' => \$should_bar); my $value = $should_foo ? foo() : bar(); print $value; } sub foo { return "Foo to you too\n"; } sub bar { return "The best bar none\n"; } 1;
    Now in you tests, you can do stuff like this:
    use Test::More tests=>1; use Test::Exception; use Sample; is Sample->bar(), "The best bar none\n", 'bar() works'; is Sample->foo(), "Foo to you too\n", 'foo() works'; local @ARGV; # now undef dies_ok { Sample->run() } 'no args dies as expected'; like $@, qr/^usage:/, 'got a usage message';
    (Note that I have not tested this; it is simply meant to be an illustration of technique.)

    You package has subs that can be tested now to see if they do what they are supposed to. I hope this points you toward a workable direction.

    Edit: Not sure why this is getting down voted - would someone care to comment? Do you disagree with the technique? Do you feel I should have solved the problem more completely? Actual feedback is more useful.