--- Tony Frasketi <[EMAIL PROTECTED]> wrote:

> I'm a newbee... Could you plase explain why it is easier to test a 
> module out than a CGI script and are you refering to modules you 
> yourself have created or modules other have created.

When you get used to automated testing, you find that modules are much
easier to load and run tests against.  For example, consider the
following snippet of code.

  # Note that this is *not* how I would write this, but it
  # illustrates the point.

  package Foo;

  use warnings;
  use strict;
  use base 'Exporter';
  our @EXPORT_OK = qw/get_customer/;
  use My::Customer;

  sub get_customer {
    my $cgi = shift;
    my $_id = $cgi->param('customer_id') || '';

    if ( my ($id) = $_id =~ /^(\d+)$/ ) {
      return My::Customer->new($id);
    }
    else {
      die "Bad customer id";
    }
  }

  1;

And later in a test, it's easy to make sure it does what you want:

  use Test::More qw/no_plan/;

  my $module = 'Foo';
  use_ok $module, 'get_customer' or die "Could not load $module";
  can_ok __PACKAGE__, 'get_customer'; # get_customer was exported

  my $cgi = $cgi->new( {customer_id => $customer_id});
  ok my $cust = get_customer($cgi), 
    '... and we should be able to get a customer';
  isa_ok $cust, 'My::Customer';

As you can see, but putting things into packages, we can make nicely
encapsulated functions or methods.  By depending only on what they
accept and not having side-effects, it's very easy to write tests for
them.  As a result, when you're testing some other code that
accidentally passes in a DBI object to get_customer(), it blows up
nicely, you find out from your tests (instead of your customers calling
to complain) and it's easy to fix.

Once I started testing, my code quality and overall productivity have
gone up quite a bit.  Quality goes up because I discovered that code
which is easy to test is generally better code.  Productivity has gone
up because developing higher quality code and constantly refactoring
means that my code base is much easier to work with.  I'm rarely
"hacking around problems".

Cheers,
Ovid

-- 
If this message is a response to a question on a mailing list, please send
follow up questions to the list.

Web Programming with Perl -- http://users.easystreet.com/ovid/cgi_course/

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to