2011-03-01 124 views
2

PHPUnit的測試:的PHPUnit不會拋出異常

public function testSizeOver64K() { 
     try { 
      $this->login(); 
      $scriptname = 'test script4'; 
      $this->fixture->installScript($scriptname, $this->scripts[$scriptname]); 
     } 
     catch (Exception $expected) { 
      return; 
     } 
     $this->fail('An expected exception has not been raised.'); 

    } 

函數的方法調用

function installScript($scriptname, $script, $makeactive = false) 
    { 
     $this->cmdPutScript($scriptname, $script); 

     if ($makeactive) 
      $this->cmdSetActive($scriptname); 

     return true; 
    } 
private function cmdPutScript($scriptname, $scriptdata) 
    { 
     if (self::STATE_TRANSACTION != $this->state) { 
      $msg = 'Not currently in TRANSACTION state'; 
      $code = 1; 
      throw new Exception($msg, $code); 
     } 

     $stringLength = $this->getLineLength($scriptdata); 

     $this->doCmd(sprintf("PUTSCRIPT \"%s\" {%d+}\r\n%s", $scriptname, $stringLength, $scriptdata)); 

     return true; 
    } 
private function getLineLength($string) { 
     if (extension_loaded('mbstring') || @dl(PHP_SHLIB_PREFIX.'mbstring.'.PHP_SHLIB_SUFFIX)) { 
      $lenght = mb_strlen($string,'8bit'); 
      if ($lenght > 65536) { 
       $msg = "Script is over 64K"; 
       throw new Exception($msg); 
      } 
      return $lenght; 
     } else { 
      $lenght = strlen($string); 
      if ($lenght > 65536) { 
       $msg = "Script is over 64K"; 
       throw new Exception($msg); 
      } 
      return $lenght; 
     } 
    } 

有人能給出提示,爲什麼PHPUnit的犯規捕獲異常?

+0

對不起,不知道爲什麼$ this-> fixture-> installScript不能如你所期望的那樣工作。錯誤報告是否打開?也許使用調試器:)或者在 - > installScript調用之前輸入一些輸出,並將其放入cmdPutScript中,以查看代碼是否真正在那裏工作。 ---我沒有看到任何理由爲什麼phpunit會導致一個問題,所以我只需要猜測它是你的代碼 – edorian 2011-03-02 08:38:03

+0

當我運行原始代碼,它作爲suposed和拋出異常。看起來由於某些原因,phpunit不執行installScript() – martins 2011-03-02 08:44:34

回答

3

使用一個調試器,並逐步通過測試用例,以確保您的代碼實際上首先拋出Exception。從代碼中不可能知道環境是否以導致異常的方式進行安裝。


在旁註上,你應該拋出較少的泛型異常。您正在使用try/catch所以下面並不適用於手頭的問題,但是請注意

實現GH-88:@ExpectedException(和setExpectedException())不再接受例外的預期異常類。

changelog for PHPUnit 3.6https://github.com/sebastianbergmann/phpunit/pull/88

2

機會是問題出在你的代碼,而不是使用PHPUnit的。

看到這個測試案例:

<?php 

function foo() { 
    throw new Exception("boom"); 
} 
class MyFooTest extends PHPUnit_Framework_TestCase { 

    public function testArguments() { 
     try { 
      foo(); 
     } catch (Exception $e) { 
      return; 
     } 
     $this->fail("nope"); 

    } 
} 

它打印:

phpunit mep.php 
PHPUnit 3.5.12 by Sebastian Bergmann. 

. 

Time: 0 seconds, Memory: 3.00Mb 

OK (1 test, 0 assertions) 

所以歸結爲它工作的要領。這將是非常奇怪的,如果phpunit會改變任何這種行爲