我正在对需要用户输入的组件进行单元测试。如何告诉 Test::More 使用我预定义的一些输入,这样我就不需要手动输入它了?

这就是我现在所拥有的:

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;

该代码确实按回车键,但是该函数正在检索0而不是1;

最佳答案

以下最小脚本似乎有效:

#!/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');
}

输出:

C:\ Temp> t
1..1
OK 1-对象是TestClass

07-26 08:52
查看更多