Override printing functions (mocking)


Sometimes there are functions that print directly to the screen.

The program could be tested as an external application or we can redirect the STDOUT to a scalar variable in the memory of perl but it might be cleaner to replace the display function, capture the data in a variable and then check that variable.


examples/test-perl/t/display.t
use strict;
use warnings;

use lib 'lib';
use MyTools;

use Test::More tests => 1;


my @data;
{
    no warnings 'redefine';
    sub MyTools::display {
        push @data, \@_;
    }
}

{
    @data = ();
    print_copyright();

    like( $data[0][0],
        qr/Copyright 2000-\d{4} Gabor Szabo, all rights reserved./,
        'copyright');
}