in reply to Tests for 'printing' code

Personally, i think this is as expected and you should change you code to not print from inside your subroutine. Your subroutine should collect data and store it in a scalar and return that instead of just printing. This is a common mistake people make, thinking that subroutines should print directly to STDOUT - sometimes they should, but most of the time you are better off capturing the output and returning it. This helps lead to more reusable code. Besides, are you more interested in testing the output, or the message string?
use Test::More qw(no_plan); ok(test_foo() eq "bar"); sub print_foo_message { print "foo"; } sub test_foo { return "bar"; }

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

Replies are listed 'Best First'.
Re: Re: Tests for 'printing' code
by dda (Friar) on Oct 19, 2003 at 15:16 UTC
    Thanks, jeffa. I expected that printing from subroutines will be blamed here. :) But how you will test sub print_foo_message then? Of course, it's too simple, but it is just an example. I'm interested in testing the output, at least, I need to test the fact that something was printed.

    --dda

      You don't. :) It's just a canned message. Why do you need to test if something was printed? That's not very helpful. Instead test what is about to be printed, before you print it. In fact, you don't need to print anything at all from your test suite (except user interaction messages like "Test this?" and your own debugging when your test has "bugs").

      Now, don't get me wrong - what you originally wanted can be done, but do you really want to go there?

      use IO::Scalar; use Test::More qw(no_plan); my $string; tie *STDOUT, 'IO::Scalar', \$string; ok(test_foo() eq 'bar'); ok($string eq 'foo'); $string = ''; ok(test_bar() eq 'baz'); ok($string eq 'bar'); $string = ''; sub test_foo { print 'foo'; return 'bar'; } sub test_bar { print 'bar'; return 'baz'; }
      No thanks. :)

      jeffa

      L-LL-L--L-LL-L--L-LL-L--
      -R--R-RR-R--R-RR-R--R-RR
      B--B--B--B--B--B--B--B--
      H---H---H---H---H---H---
      (the triplet paradiddle with high-hat)
      
        No thanks, just ++jeffa. ;)

        --dda