Consider the following code in a model. the function deleteUser(NULL) will trigger an 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!");
}
}
}
I use PHPUnit to test this code and I want to check that the exception is indeed triggered when NULL is passed to the function deleteUser. The code in the testing class goes as follows:
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);;
}
}
While this seems to work, I am wondering if there is a better way to do this. I have reviewed questions:
PHPUnit assert that an exception was thrown?
Problem testing exceptions with PHPUnit and Zend Framework
But I did not fully understand them / see how that applies in this case (testing a model, not a controller).
Any better way to test the exception is thrown? Any advice will be much appreciated.