develooper Front page | | Postings from August 2004

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

Thread Previous | Thread Next
August 24, 2004 17:47
Re: Test::Harness with modules that output to STDOUT
Message ID:
--- Peter Kay <> 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)


Silence is Evil  
Web Programming with Perl

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About