How can I unit test Perl functions that print to the screen?

后端 未结 3 524
广开言路
广开言路 2020-12-28 13:31

I\'m trying to use Test::More to unit test Perl functions that print to the screen.

I understand that this output may interfere with tools such as prove.

How

3条回答
  •  灰色年华
    2020-12-28 13:35

    If this is code that you are writing yourself, change it so that the print statements don't use a default filehandle. Instead, give yourself a way to set the output filehandle to anything you like:

    sub my_print {
         my $self = shift;
         my $fh = $self->_get_output_fh;
         print { $fh } @_;
         }
    
    sub _get_output_fh { $_[0]->{_output}  || \*STDOUT }
    sub _set_output_fh { $_[0]->{_output} = $_[1] } # add validation yourself
    

    When you test, you can call _set_output_fh to give it your testing filehandle (perhaps even an IO::Null handle). When another person wants to use your code but capture the output, they don't have to bend over backward to do it because they can supply their own filehandle.

    When you find a part of your code that is hard to test or that you have to jump through hoops to work with, you probably have a bad design. I'm still amazed at how testing code makes these things apparent, because I often wouldn't think about them. If it's hard to test, make it easy to test. You generally win if you do that.

提交回复
热议问题