2012-07-24 22 views
0

考慮模型中的以下代碼。函數deleteUser(NULL)將觸發異常。Zend PHPUnit測試模型,斷言Zend_Exception確實發生如預期

class Model_UserModel extends Zend_Db_Table_Abstract{ 
    protected $_name = 'users'; 
    protected $_primary = 'id'; 
    public function deleteUser($id){ 
    $row=$this->find($id)->current(); 
     if($row){ 
      $row->delete(); 
      return true; 
     }else{ 
      throw new Zend_Exception("Delete function failed; could not find row!"); 
     } 
    } 
} 

我使用PHPUnit來測試這段代碼,我想檢查當NULL傳遞給函數deleteUser時確實觸發了異常。在測試類代碼如下:

class Application_Model_UserModelTest extends PHPUnit_Framework_TestCase{ 
    ... 
    //deleting a user with ID=NULL should fail 
    public function testDeleteNull(){ 
     $e = null; 
     try{ 
      $this->_users->deleteUser(NULL); 
     }catch (Exception $e) {} 
     if($e) { 
      $this->assertTrue(TRUE); 
     }else{ 
      $this->assertTrue(FALSE);; 
     } 
    } 

雖然這似乎工作,我想知道是否有更好的方法來做到這一點。我已審查問題:

PHPUnit assert that an exception was thrown?

Problem testing exceptions with PHPUnit and Zend Framework

但我不完全理解他們/怎麼看,在這種情況下(測試模式,而不是一個控制器)適用。

任何更好的方法來測試異常被拋出? 任何意見將不勝感激。

回答

1

你這樣做的一個問題是,它接受任何異常,因爲所有異常繼承自Exception。所以你可能會錯過一個bug,因爲拋出的異常不是你所期望的異常。

使用註釋。

/** 
* @expectedException Zend_Exception 
*/ 
public function testDeleteNull(){ 
$this->_users->deleteUser(NULL); 
} 

雖然您可能想要創建自定義異常類,但要更準確。有些人會爭辯說,使用exceptedException你不能斷言異常消息,他們是正確的。簡單地說,它沒有普遍和「正確」的解決方案。

+0

事實上,無論觸發什麼異常,它都會聲明爲真。好的建議,謝謝。 – 2012-09-06 06:34:01