【问题标题】:phpunit runs test twice - gets two answers. Why?phpunit 运行测试两次 - 得到两个答案。为什么?
【发布时间】:2010-10-07 14:26:56
【问题描述】:

这是我的 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 为空。

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

这是 phpunit 的 bug 还是我对 php 的理解?

【问题讨论】:

    标签: php phpunit


    【解决方案1】:

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

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

    1. test01 准备好了
    2. 备份由所有全局变量组成(此时全局范围内的$actions没有设置,因为代码还没有运行)
    3. test01 运行
    4. demo.php 包含在内(感谢自动加载),并且 $actions 设置在全局范围内
    5. 您的断言成功,因为 $actions 设置在全局范围内
    6. test01 被拆除。全局变量返回到它们的原始值。全局范围内的 $actions 在此时被销毁,因为它被设置在内部测试中,在测试开始之前它不是全局状态的一部分
    7. test02 运行 .. 失败,因为全局范围内没有 $actions。

    直接解决您的问题:在 DemoTest.php 的开头包含 demo.php,这样 $actions 会在每次测试前后备份和恢复的全局范围内结束。

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

    【讨论】:

      猜你喜欢
      • 2022-01-12
      • 1970-01-01
      • 2017-04-20
      • 2012-09-12
      • 2015-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      相关资源
      最近更新 更多