perl - 我如何在 Perl 测试中模拟 %ENV?

我正在尝试使用 Test::More 将一些测试改造为遗留代码,但我遇到了一些障碍。我似乎无法在测试模块中设置 %ENV。被调用的函数肯定会使用此变量,因此 %ENV 似乎不会传递给测试对象。

#!/usr/bin/perl

use strict; use warnings;
use Test::More qw(no_plan);

BEGIN {
    $ENV{HTTP_WWW_AUTHENTICATE} = 
        'WWW-Authenticate: MyType realm="MyRealm",userid="123",password="abc"';
    use_ok('Util');
}

$ENV{HTTP_WWW_AUTHENTICATE} = 
    'WWW-Authenticate: MyType realm="MyRealm",userid="123",password="abc"';

printf qq{get_authentication_info = "%s"\n}, get_authentication_info();
ok(get_authentication_info(), 'Get authentication info');

我不断得到...

perl t\Util.t
ok 1 - use Util;
Use of uninitialized value in concatenation (.) or string at t\Util.t line 14.
get_authentication_info = ""

As with all things Perl, I'm pretty sure that some one has done this before.

UPDATE: Thanks to all for your help

The problem was between the keyboard & chair ... My test data was just plain wrong It needed to be

$ENV{HTTP_WWW_AUTHENTICATE} = 
    'MyType realm="MyRealm",userid="123",password="abc"';

最佳答案

正如思南所说,$ENV{...} 行被注释掉了,所以它不能工作。但如果您想要真正可测试的代码,我建议让 get_authentication_info 函数将散列作为参数。这样你就可以在不设置全局变量的情况下对其进行测试,并且在真实代码中你可以传递真实的环境哈希。全局状态最终总会成为一个问题。

https://stackoverflow.com/questions/1579831/

相关文章:

visual-studio-2008 - Visual Studio 中的 "Detach All"

sql - 是否有适用于所有数据库的标准sql

perl - 为什么我的 CGI 脚本提示 "Can' t locate CGI/Session.p

sql - 调用 'Fill' 之前 SelectCommand 属性尚未初始化

vb.net - 如何检查DataReader是否有数据?

vb.net - 配置系统无法在 .NET 中初始化

unix - 真正了解网络?

regex - 带数字的 CSV 正则表达式

vb.net - 如何从消息框中获取结果?

bash - 将 bash 中的逗号分隔数据包装成固定的行长度