使用PHPUnit时,全局变量为null [英] global variables are null when using PHPUnit

查看:136
本文介绍了使用PHPUnit时,全局变量为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将PHPUnit测试放入现有项目中.全局常数变量被广泛使用.在我的单元测试中,函数失败,因为全局变量为null.这是测试失败的示例

I am putting PHPUnit testing into an existing project. Global constants variables are used extensively. In my unit test functions are failing because the global variables are null. Here is an example of a failing test

static $secret_key = "a secret Key";
class secret_key_Test extends PHPUnit_Framework_TestCase
{
    function test_secret_key()
    {
        global $secret_key; 
        $this->assertEquals($secret_key, "a secret Key");   
    }
}

>> Failed asserting that 'a secret Key' matches expected null

任何帮助将不胜感激

更新: 我尝试删除静态并添加

Update: I have tried removing static and adding

protected $backupGlobals = FALSE;

没有成功的类声明.

推荐答案

此答案无效.我在此处提出了几乎相同的问题,最后给出了更有意义的答案;您不能覆盖PHPUnit将看到的测试类中的受保护属性$ backupGlobals.如果您在命令行上运行,则似乎可以通过创建xml配置文件并在此处将backupGlobals设置为false来使Globals正常工作.

This answer doesn't work. I asked a virtually identical question here and wound up with an answer that makes more sense; you can't overwrite the protected property $backupGlobals in the test Class that PHPUnit will see. If you're running on the command line, it seems that you can get Globals to work by creating an xml configuration file and setting up backupGlobals to false there.

使用PHPUnit时,您需要同时声明$ secret_key全局和在全局空间为其分配一个值. PHP默认将全局初始化的变量放置到全局名称空间中,但是在备份全局变量时,PHPUnit会更改此默认值!

You need to declare $secret_key both global and assign a value to it in the global space when using PHPUnit. PHP defaults to placing globally initialized variables into the global namespace, but PHPUnit changes this default when backing up globals!

需要进行以下更改:

global $secret_key; // Declaring variable global in global namespace
$secret_key = "a secret Key"; // Assigning value to global variable

您的代码应该可以正常工作了.

Your code should work now.

这篇关于使用PHPUnit时,全局变量为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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