Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
重构perl sub以实现可测试性_Perl_Unit Testing_Refactoring - Fatal编程技术网

重构perl sub以实现可测试性

重构perl sub以实现可测试性,perl,unit-testing,refactoring,Perl,Unit Testing,Refactoring,我继承了一个perl代码库。考虑下面的子程序; sub getSysRTable { my $iface = shift; return if not length($iface); my %ip_routes; my @routes = `/usr/bin/netstat -rn`; foreach my $route(@routes) { if ($route =~ /([\S.]+)\s+([\d.]+.[\d.]+.[\d.]+.[

我继承了一个perl代码库。考虑下面的子程序;
sub getSysRTable
{
    my $iface = shift;
    return if not length($iface);
    my %ip_routes;
    my @routes = `/usr/bin/netstat -rn`;
    foreach my $route(@routes) {
        if ($route =~ /([\S.]+)\s+([\d.]+.[\d.]+.[\d.]+.[\d.]+)\s+(UGS|UGHS)\s+($iface)/ )
            { $ip_routes {$1} = $2 }
    }
    return %ip_routes;
}
我想为这段代码编写单元测试。我想到的测试将使用
netstat-rn
的样本输出,并检查预期的行为。sub原样调用一个命令,因此注入我的测试数据在这个实现中是有问题的


什么是惯用的perlish方法来重构此sub以实现可测试性?

首先,按如下方式更改代码:

sub getDataForSysRTable {
    return `/usr/bin/netstat -rn`;
}

sub getSysRTable
{
    my $iface = shift;
    return if not length($iface);
    my %ip_routes;
    my @routes = getDataForSysRTable();
    foreach my $route(@routes) {
        if ($route =~ /([\S.]+)\s+([\d.]+.[\d.]+.[\d.]+.[\d.]+)\s+(UGS|UGHS)\s+($iface)/ )
            { $ip_routes {$1} = $2 }
    }
    return %ip_routes;
}
那么对于你的测试,你可以

local *getDataForSysRTable = sub { 
   ... return known data ...
};

my $ip_routes = getSysRTable($iface);

另请参见,on*nix
netstat-r
只是从/proc/net/route提取数据,所以您可以直接解析它