2010-10-07 70 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