2010-10-07 71 views
5

这是我的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'); 
     } 
    } 
} 
?> 

文件的结果是,因为$行为是无效的第二次测试失败。

我的问题是 - 为什么我没有得到两个测试相同的结果?

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

回答

3

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

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

  1. TEST01准备
  2. 备份的所有全局变量(在这一点上在全球范围内$行动没有设置,因为代码没有跑还)
  3. TEST01运行
  4. 演示。 php包含了(感谢autoload)并且$ actions在全局范围内设置了
  5. 您的断言成功了,因为$ actions在全局范围内设置了
  6. test01被拆除。全局变量返回到它们的原始值。在全球范围内$行动是在这一点上破坏,因为它被设置测试,它不是全局状态的一部分,测试
  7. test02运行..和失败开始前,因为有在全球范围内没有$动作。

直接修复问题的方法:包括DemoTest.php年初demo.php,这样$行动在备份前和每次测试后恢复全球范围内结束。

长期修复:尽量避免使用全局变量。它只是一个坏习惯,总是比全球使用“全球化”的国家更好。

+1

多么好的答案 - 谢谢。它现在变得非常灵敏。 – Ian 2010-10-12 09:32:24