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;
STDIN in Perl is used to take input from the keyboard unless its work has been redefined by the user. In order to take input from the keyboard or operator is used in Perl. This operator reads a line entered through the keyboard along with the newline character corresponding to the ENTER we press after input.
Taking command line arguments means to pass some argument (or give input) while calling this command to run a Perl script. For example, to give 5 as input, writing this command - perl filename.pl 5 or to pass both 5 and 10, writing this - perl filename.pl 5 10. We do this by using @ARGV array.
If the program reads from STDIN
, then just set STDIN
to be the open filehandle you want it to be:
#!perl use strict; use warnings; use Test::More; *STDIN = *DATA; my @a = <STDIN>; is_deeply \@a, ["foo\n", "bar\n", "baz\n"], "can read from the DATA section"; my $fakefile = "1\n2\n3\n"; open my $fh, "<", \$fakefile or die "could not open fake file: $!"; *STDIN = $fh; my @b = <STDIN>; is_deeply \@b, ["1\n", "2\n", "3\n"], "can read from a fake file"; done_testing; __DATA__; foo bar baz
You may want to read more about typeglobs in perldoc perldata
and more about turning strings into fake files in the documentation for open
(look for "Since v5.8.0, perl has built using PerlIO by default.") in perldoc perlfunc
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With