phpunit运行测试两次 - 获得两个答案。为什么?

时间:2010-10-07 14:26:57

标签: php phpunit

这是我的phpunit测试文件

<?php // DemoTest - test to prove the point

function __autoload($className) {
    //  pick file up from current directory
    $f = $className.'.php'; 
    require_once $f;
}

class DemoTest extends PHPUnit_Framework_TestCase {
    // call same test twice - det different results 
    function test01() {
        $this->controller = new demo();
        ob_start();
        $this->controller->handleit();
        $result = ob_get_clean();  
        $expect = 'Actions is an array';
        $this->assertEquals($expect,$result);
    }

    function test02() {
        $this->test01();
    }
}
?>

这是受测试的文件

<?php // demo.php
global $actions;
$actions=array('one','two','three');
class demo {
    function handleit() {
        global $actions;
        if (is_null($actions)) {
            print "Actions is null";
        } else {
            print('Actions is an array');
        }
    }
}
?>

结果是第二次测试失败,因为$ actions为null。

我的问题是 - 为什么我不能在两次测试中获得相同的结果?

这是phpunit中的错误还是我对php的理解?

1 个答案:

答案 0 :(得分:3)

PHPUnit有一个名为“备份全局变量”的功能,如果打开,那么在测试开始时,全局范围内的所有变量都会被备份(快照由当前值组成),并且在每次测试完成后,值将再次恢复到原始值。您可以在此处详细了解:http://sebastian-bergmann.de/archives/797-Global-Variables-and-PHPUnit.html#content

现在让我们来看看你的测试套件。

  1. 准备了test01
  2. 备份由所有全局变量组成(此时未设置全局范围内的$ actions,因为代码尚未运行)
  3. test01运行
  4. demo.php包含在内(感谢autoload),$ actions在全局范围内设置
  5. 您的断言成功,因为$ actions设置在全局范围内
  6. test01被拆除。全局变量返回其原始值。此时全局范围内的$操作已销毁,因为它在测试中设置了 ,它在测试开始之前不是全局状态的一部分
  7. test02运行..并失败,因为全局范围内没有$ actions。
  8. 直接修复您的问题:在DemoTest.php的开头包含demo.php,这样$ actions就会在每次测试之前和之后备份和恢复的全局范围内结束。

    长期修复:尽量避免使用全局变量。它只是一个坏习惯,总有比使用“全球”的全球状态更好的解决方案。

相关问题