develooper Front page | perl.qa | Postings from August 2004

Re: Test::Harness with modules that output to STDOUT

Thread Previous | Thread Next
From:
Ovid
Date:
August 24, 2004 17:47
Subject:
Re: Test::Harness with modules that output to STDOUT
Message ID:
20040825004742.68806.qmail@web60808.mail.yahoo.com
--- Peter Kay <peterkayatwork@yahoo.com> wrote:
> Ok, what's the elegent way to ignore/dispose of the output the tested 
> module produces?

What I do whenever this happens is to move the printing code to a subroutine or method and
override that to capture the output.  So if I have something like this:

  sub Foo::_print {
    print shift;
  }

In my test, I have something like this:

  my $_print;
  *Foo::_print = sub { $_print = shift };
  is($_print, $expected, "Foo::_print output the correct data");

This has several benefits.  Not only do you not worry about how Test::Harness will react, you also
have the ability to test the printed data, something which is frequently not done.  Also, I've
found that by refactoring such functionality into one subroutine, I later have a convenient place
to alter the behavior, if necessary, rather than hunt through the code.  I've found this to be
very useful if I need to send the data to different destinations or add behavior such as emailing
critical error messages or reports.

If you hate using typeglobs:

  use Sub::Override; # disclaimer:  I wrote it.
  my $_print;
  my $override = Sub::Override->new('Foo::_print' => sub { $_print = shift });

(You can later restore the subroutine, if needed)

Cheers,
Ovid

=====
Silence is Evil            http://users.easystreet.com/ovid/philosophy/indexdecency.htm
Ovid                       http://www.perlmonks.org/index.pl?node_id=17000
Web Programming with Perl  http://users.easystreet.com/ovid/cgi_course/

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About