yuri123 has asked for the wisdom of the Perl Monks concerning the following question:

I want to test STDOUT/STDERR of a Perl module I wrote. The test code I started with is along the lines:
... use Test::More; plan tests => 1; BEGIN { use_ok( 'Module' ) || print "Bail out!\n"; } ... my $obj = Module->new; $obj->run; # Will emit STDOUT I want to capture and verify
Any advice would be greatly appreciated.

Replies are listed 'Best First'.
Re: How to capture and verify STDOUT of a Perl Module
by Perlbotics (Archbishop) on Jul 29, 2013 at 18:11 UTC

    Test::Output already seems to do what you want.

    stdout_like( sub{ $obj->run }, qr/as expected regex/, 'output as expe +cted' );

    Update (response to CR below): When capturing output from an external process, try IO::CaptureOutput:

    use strict; use warnings; use Test::More; use Test::Output; use IO::CaptureOutput qw(capture); sub writer { system("echo Hubba") }; #fails: stdout_like( \&writer, qr/Hubba/ms, "it's a hubba" ); capture { writer() } \my $stdout, \my $stderr; is( $stdout, "Hubba\n", "system hubba" ); done_testing; #-- output: # # ok 1 - system hubba # 1..1

      I tried Test::Output. It looks like it did not capture the output from a system() that Module issues.
        it did not capture the output from a system()
        system does not return a command's output (only its exit status). Perhaps you want qx.
Re: How to capture and verify STDOUT of a Perl Module
by toolic (Bishop) on Jul 29, 2013 at 18:20 UTC
Re: How to capture and verify STDOUT of a Perl Module
by tobyink (Canon) on Jul 29, 2013 at 21:39 UTC
    #!/usr/bin/env perl use strict; use warnings; use Test::More; use Capture::Tiny 'capture'; BEGIN { use_ok('Module') || print "Bail out!\n"; } my $obj = 'Module'->new; my $out = capture { $obj->run }; like($out, qr/^Awesome/); done_testing;
    package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name