0

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.

1 Answer 1

1

A problem with the way you do it is that it accepts any exception since all exceptions inherit from Exception. So you may miss a bug because the exception thrown was not the exception you expected.

Use annotations.

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

You might want to create custom exception class to be more accurate though. Some people will argue that using exceptedException you can't assert the exception message and they are right. Simply there isn't universal and 'correct' solution for it.

1
  • Indeed, it will assert true whatever the exception triggered. Good advice, thanks. Commented Sep 6, 2012 at 6:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.