How can I fake STDIN in Perl?

perl, unit-testing

Solution

The following minimal script seems to work:

#!/usr/bin/perl

package TestClass;
use strict;
use warnings;

sub new {
    my $class = shift;
    return unless <STDIN> eq "1\n";
    bless {} => $class;
}

package main;

use strict;
use warnings;

use Test::More tests => 1;

{
    open my $stdin, '<', \ "1\n"
        or die "Cannot open STDIN to read from string: $!";
    local *STDIN = $stdin;
    my $test = TestClass->new;
    isa_ok( $test, 'TestClass');
}

Output:

C:\Temp> t
1..1
ok 1 - The object isa TestClass

Problem

I am unit testing a component that requires user input. How do I tell `Test::More` to use some input that I predefined so that I don't need to enter it manually? This is what I have now: ``` use strict; use warnings; use Test::More; use TestClass; *STDIN = "1\n"; foreach my $file (@files) { #this constructor asks for user input if it cannot find the file (1 is ignore); my $test = TestClass->new( file=> @files ); isa_ok( $test, 'TestClass'); } done_testing; ``` This code does press enter but the function is retrieving 0 not 1;

Original source