Perl tests in your class

By Tim Keefer
Oct 22 2007 4:37 p.m.

Java has inspired me to think about Perl testing in a Java like fashion. I've always been a fan of placing tests into the class, as opposed to a separate test script. To accomplish this style of testing I used Test::Builder and since it's a Singleton the tests can easily work together or work independently.

I see it this way; there are two basic ways to run the class tests.

1) Run the tests for a single class from the command line

 perl -Ilib -mSunflower::Queue -e 'Sunflower::Queue->run_tests;'

2) Create a batch test script (01class.t) to crawl your distribution looking for *.pm and execute the class run_tests method

package Sunflower::Queue;

use strict;
use warnings;
use Amazon::SQS::Simple;

sub new {
   my ( $class, $access_key, $secret_key ) = ( shift, shift, shift );

   $access_key ||= 'somekey';
   $secret_key ||= 'secretkey';

   my $self = {};
   bless( $self, $class );

   # create and instance of SQS
   $self->queue_service(
       Amazon::SQS::Simple->new( $access_key, $secret_key )
   );

   return $self;
}

sub run_tests {
   my $class = shift;

   require Test::Builder;

   my $test = Test::Builder->new();

   $test->no_plan;
   $test->diag( 'testing ' . __PACKAGE__ );

   my $o = __PACKAGE__->new();

   for ( 1 .. 10 ) {
       $test->is_eq( $o->test_method, 'tim', "test return value" );
   }

}

# sample method
sub test_method {
   my $self = shift;
   return 'tim';
}

# Queue stuff
sub ListQueues {
   my $self = shift;
   $self->queue_service->ListQueues( @_ );
}
Post a comment

sometimes it feels reaally good to sit
Attachments
Sunflower::Queue (2.6K)
01class.t (890)