简体   繁体   English

在 perl 中进行单元测试时,如何模拟 GLOB ref 的实数?

[英]How do I mock a realine of a GLOB ref when unit testing in perl?

For example in the following code how do I mock readline to unit test the do_stuff routine?例如,在下面的代码中,我如何模拟 readline 来对 do_stuff 例程进行单元测试?

I think I require我想我需要

  1. $sock must be a GLOB reference. $sock 必须是 GLOB 引用。
  2. readline() must be mocked. readline() 必须被模拟。

I tried using FileHandle->new but got error - "readline() on unopened filehandle GEN1" which I took as readline() wasn't being mocked.我尝试使用 FileHandle->new 但得到错误 - “readline() on unopened filehandle GEN1”我认为 readline() 没有被嘲笑。

I tried an Test::MockObject (not extends), with readline() mocked, but that had the error "Not a GLOB reference" which reminded me that readline() isn't being called as a method.我尝试了一个 Test::MockObject(不是扩展),并模拟了 readline(),但它有错误“不是 GLOB 引用”,这提醒我 readline() 没有被作为方法调用。

package MyIO;

sub get_sock{ return IO::Socket::INET->new(@tcp_arg); }

sub do_stuff {
    my $sock = get_sock();
    my $line1 = <$sock>;
    my $line2 = readline($sock);
    return;
}

package TestMyIO;

sub test_do_stuff{
    # my $mock_sock = Test::MockObject::Extends->new(IO::Socket::INET->new);

    my $mock_sock = die("TODO");
    my @fake_lines = ('line 1', 'line 2', 'line 3');

    no warnings 'redefine';    ## no critic (ProhibitNoWarnings)
    local *MyIO::get_sock = sub { return $mock_sock; };
    local *MyIO::readline = sub { return shift @fake_lines; };
    use warnings 'redefine';

}

You can use the following:您可以使用以下内容:

open(my $fh, '<', \$str);

This won't work if a system file handle is needed (eg if the handle needs to survive an exec ).如果需要系统文件句柄(例如,如果句柄需要在exec存活),这将不起作用。 But as long as you stick to Perl, reads from the handle will read from the provided buffer.但是只要您坚持使用 Perl,从句柄中读取的内容就会从提供的缓冲区中读取。

Builtins like readline must be mocked in the CORE::GLOBAL namespace, and must generally be defined at compile-time.readline这样的内置函数必须在CORE::GLOBAL命名空间中模拟,并且通常必须在编译时定义。

my @fake_lines;
BEGIN {
    *CORE::GLOBAL::readline = sub { shift @fake_lines };
}
@fake_lines = ('line 1','line 2','line 3');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM