使用PHPUnit时,全局变量为null

时间:2012-01-31 01:08:05

标签: php phpunit

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

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

非常感谢任何帮助

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

protected $backupGlobals = FALSE;

对班级宣言没有成功。

3 个答案:

答案 0 :(得分:11)

这个答案不起作用。我问了一个几乎完全相同的问题here,最后给出了一个更有意义的答案;你不能覆盖PHPUnit将看到的测试类中的受保护属性$ backupGlobals。如果你在命令行上运行,似乎你可以通过创建一个xml配置文件并在那里将backupGlobals设置为false来使Globals工作。

编辑:您需要声明$ secret_key全局并在使用PHPUnit时在全局空间中为其分配值。 PHP默认将全局初始化变量放入全局命名空间,但PHPUnit在备份全局变量时更改了此默认值!

需要进行以下更改:

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

您的代码现在应该可以使用。

答案 1 :(得分:5)

你应该问phpunit不要备份全局

protected $backupGlobals = FALSE;
就像在S. Bergmann的原始文章中所说:http://sebastian-bergmann.de/archives/797-Global-Variables-and-PHPUnit.html

答案 2 :(得分:0)

您必须在引导测试时设置全局变量。这是我如何编写测试的示例代码

    /**
     * Class to allow us set product on the fly
     */
    class Product
    {
        public function __call($method, $args)
        {
            if (isset($this->$method)) {
                $func = $this->$method;
                return call_user_func_array($func, $args);
            }
        }
    }

    /**
     * UssdShortcode Tester
     */
    class ShortCodeTester extends WP_UnitTestCase {

        protected  $product;

        public function setUp()
        {   
            $this->product            = new Product;
            $this->product->get_id    = function(){ return 50; };

            $GLOBALS['product']       = $this->product;
        }

        /**
         * A single example test.
         */
        function test_it_can_display_ussd_shortcode() {

            $displayer = new UssdShortCodeDisplayer;
            $expected  = view('show-product-short-code',['product_id' => $this->product->get_id() ]);
            $results   = $displayer->display($this->product->get_id());

            // $this->assertRegexp('/'.$expected.'/', $results);
            $this->assertEquals($expected,$results);
        }
    }
相关问题