如何在 Perl 中伪造 STDIN? [英] How can I fake STDIN in Perl?

查看:51
本文介绍了如何在 Perl 中伪造 STDIN?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这就是我现在所拥有的:

使用严格;使用警告;使用测试::更多;使用测试类;*STDIN = "1\n";foreach 我的 $file (@files){#此构造函数在找不到文件时要求用户输入(1 是忽略);我的 $test = TestClass->new( file=> @files );isa_ok($test, 'TestClass');}done_testing;

这段代码确实按下了回车,但函数正在检索 0 而不是 1;

解决方案

以下最小脚本似乎有效:

#!/usr/bin/perl封装测试类;使用严格;使用警告;子新{我的 $class = shift;返回除非 <STDIN>等式1\n";祝福 {} =>$class;}包主;使用严格;使用警告;使用测试::更多测试=>1;{打开我的 $stdin, '<', \ "1\n"或者死无法打开标准输入读取字符串:$!";本地 *STDIN = $stdin;我的 $test = TestClass->new;isa_ok($test, 'TestClass');}

输出:

<前>C:\Temp> t1..1ok 1 - 对象是 TestClass

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;

解决方案

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

这篇关于如何在 Perl 中伪造 STDIN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆