10

我正在使用 PHP 5.2.9 学习和探索 PHPUnit 的应用程序,并且遇到了全局问题。我已将 $backupGlobals 设置为 FALSE,包括文档“@backupGlobals disabled”,这似乎不会影响 PHPUnit 备份全局变量的行为。有什么我想念的吗?我需要更改 PHPUnit 的 xml 文件吗?创建引导程序?

配置.php:

$testString = 'Hello world!';

基本应用程序.php:

require ('D:\data\clients\security.ca\web_sites\QRASystems.com\wwwroot\__tests\BasicApp\config.php');

class BasicApp {

public $test;

public function __construct() {
    global $testString;
    $this->test = $testString;
}

public function getTest() {
    return $this->test;
}

public function setTest($test){
    $this->test = $test;
}

BasicAppTest.php:

require ('D:\data\clients\security.ca\web_sites\QRASystems.com\wwwroot\__tests\BasicApp\BasicApp.php');

class BasicAppTest extends PHPUnit_Framework_TestCase{
    protected $testClass;
    protected $backupGlobals = FALSE;
    protected $backupGlobalsBlacklist = array('testString');

    public function SetUp(){
        $this->testClass = new BasicApp;
        $this->testClass->bootstrap();
    }

    public function testGlobal(){
        echo $this->testClass->getTest();
        $this->assertNotNull($this->backupGlobals);
        $this->assertFalse($this->backupGlobals);
        $this->assertNotEmpty($this->testClass->test);
    }

    public function testMethods(){
        $this->testClass->setTest('Goodbye World!');
        echo $this->testClass->getTest();
        $this->assertNotNull($this->backupGlobals);
        $this->assertNotNull($this->testClass->test);
        if (empty($this->testClass->test)) echo 'Method set failed!';
    }
}

testGlobal() 在 $this->assertNotEmpty($this->testClass->test) 上失败,表明 $this->backupGlobals 设置为 FALSE 并且 PHPUnit 仍在备份全局变量。

编辑:我通过进行以下更改来完成这项工作-

BasicAppTest.php:

    protected $backupGlobals = FALSE; <- REMOVED
    protected $backupGlobalsBlacklist = array('testString');  <- REMOVED

配置.php:

global $testString; <- ADDED
$testString = 'Hello world!';

我惊呆了,这在以前没有被覆盖过!

4

2 回答 2

10

在您的测试用例中,您正在定义一个PHPUnit 看不到的 $backupGlobals属性。由于该属性是受保护的,您可以false在构造函数中将其设置为,但 PHPUnit 使用其构造函数来传递有关如何运行测试方法的信息。相反,创建一个phpunit.xml配置文件backupGlobals属性设置为false.

<phpunit backupGlobals="false">
    <testsuites>
        <testsuite name="Test">
            <directory>.</directory>
        </testsuite>
    </testsuites>
</phpunit>
于 2012-03-12T20:41:56.383 回答
2

在您的编辑和评论中,您指出了该问题的一种解决方法(在测试的应用程序中明确声明全局变量)。在onlab 对 PHPUnit 问题的评论中,他解释了这种行为:当在函数中包含文件时,PHP 将包含文件中的全局变量放入函数的范围内。PHPUnit 在函数中加载文件,虽然它尝试提取全局变量,但在我尝试过的情况下它失败了。

不幸的是,我无法在最小的测试用例中重现我的遗留系统的问题(而且我很难理解你的),所以我无法真正确认解释。但他建议的解决方法帮助了我:使用选项提供引导文件--bootstrap;在其中声明应用程序的测试部分使用的每个全局变量。这避免了为了测试它而修改应用程序的需要。这是来自 GitHub 的 onlab 示例:

phpunit --bootstrap bootstrap.php test-path

bootstrap.php

global $my, $system, $globals, $here;
require_once("/path/to/my/system/bootstrap.php");
于 2014-05-09T22:48:34.903 回答