Dirt Simple Perl Unit Example

This is how to write the simplest one-file testage for PerlUnit, with the minimum of "package" shenanigans, but with the real assertions, like assert_matches, available.

To test MyModule.pl, get inside it and instrument its main() like this:

  exit (main())  if $0 eq __FILE__;

Now MyModule.pl will run normally, as a script, from a command line, but when bonded with another module it doesn't activate its main() routine.

Now write this inside TestMyModule.pl:

 use strict;
 require 'MyModule.pl';

package TestMyModule; use base qw(Test::Unit::TestCase);

sub new { my $self = shift()->SUPER::new(@_); # your state for fixture here return $self; }

sub set_up { # provide fixture } sub tear_down { # clean up after test } sub test_foo { my $self = shift; $self->assert_matches(qr/expected result/, 'expected result');

} sub test_bar { # test the bar feature }

use Test::Unit::TestRunner;

my $testrunner = Test::Unit::TestRunner->new(); $testrunner->start('TestMyModule');

And that's it. Now you can start writing ordinary test_*() cases on MyModule's contents.

This information was scattered across various help files, and not entirely obvious to the itinerant PerlLanguage dabbler...


CategoryPerl CategoryTesting


EditText of this page (last edited January 3, 2005) or FindPage with title or text search