Skip to content

PBP part2 — Unit test your Perl script

April 3, 2012

I always heard people saying that our Perl script cannot be unit-tested because it’s not modularized. However, there is a simple way that you can write tests for your Perl script and the magic here is caller.

You used to write script like this

use strict;
use warnings;
print "hello world\n";

Now you can write like this

use strict;
use warnings;

main() unless caller();
sub main {
  print "hello world\n";

Of course, main is just a name of the main function, you can call it any way you want. run() is another pretty good name. After doing this, you can write your unit test in this way

use strict;
use warnings;

use Test::More;
use Test::Output qw( stdout_is );

require '';
stdout_is { &main::main() } "hello world\n", "Test STDOUT";

Put the code above to a.t and run the test

perl a.t
ok 1 - Test STDOUT

So here I showed two techniques

  • How to test subroutines in a Perl script
  • How to verify the output using Test::Output

From → perl

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: