2010-08-12 127 views
3

我正在用phpUnit编写一些单元测试来测试一个Zend Framework应用程序,并且我在changePassword函数中测试了一个异常时遇到了一些问题。测试不会失败,但是在生成html的覆盖工具中,“抛出新的异常($ tr-> translate('userOldPasswordIncorrect'));”线没有经过测试。未使用phpUnit进行测试的异常?

public function changePassword(array $data, $id) 
{ 
    $user = $this->_em->find('Entities\User', (int) $id); 

    $oldPassword = sha1(self::$_salt . $data['oldPassword']); 
    if ($user->getPassword() !== $oldPassword) { 
     $tr = PC_Translate_MySQL::getInstance(); 
     throw new Exception($tr->translate('userOldPasswordIncorrect')); 
    } 

    $user->setPassword(sha1(self::$_salt . $data['password'])); 

    $this->_em->persist($user); 
    $this->_em->flush(); 
} 

这应该测试异常的单元测试:

/** 
* @depends testFindByAuth 
* @expectedException Exception 
*/ 
public function testChangePasswordWrongOldPassword() 
{ 
    $this->_dummyUser = $this->_user->findByAuth($this->_dummyEmail, $this->_dummyPassword, $this->_reseller); 

    // Try to change the password with a wrong oldPassword 
    $data['oldPassword'] = 'wrongOldPassword'; 
    $data['password'] = $this->_dummyNewPassword; 

    $this->_user->changePassword($data, $this->_dummyUser->getId()); 
} 

我希望有人能告诉我什么,我做错了。

更新

问题是PC_Translate_MySQL :: getInstance()方法内。有人抛出异常。正如我正在测试的那样,通过了一个普遍的例外。解决方案不要在changePassword方法中使用常规异常。

+0

是testFindByAuth传递?如果没有,取决于不会让testChangePasswordWrongOldPassword运行。 – 2010-08-12 17:40:26

+0

testFindByAuth正在通过。 – tom 2010-08-12 17:44:22

回答

4

我的猜测是?有一个例外是从PC_Translate_MySQL::getInstance() ...

这是使用单个Exception的麻烦。这使得检查抛出什么异常变得更加困难。我建议改变changePassword方法抛出一个不同的异常。也许是InvalidArgumentExceptionRuntimeException。然后测试那个。

就我个人而言,我总是因为这个原因而使用自定义异常。

try { 
} catch (DatabaseQueryException $e) { 
    // Handle database error 
} catch (DatabaseConnectionException $e) { 
    // We never even connected... 
} catch (InvalidArgumentException $e) { 
    //... 
} 

因为这个原因,我一般不会使用catch (Exception $e)。你永远不知道你发现了什么异常。 (我有一个自定义的异常处理程序定义,所以我不致命,如果应用程序不捕获,而是显示500错误并记录异常)...

+0

这就是它。但是,那么代码覆盖率报告将显示哪个异常实际上受到了打击...... – 2010-08-12 18:06:12

+0

它会呢?当然,它会增加抛出异常,但如果像我一样,你有一堆测试,你会发现240次访问异常而不是239次? AFAIK,覆盖率报告(HTML或XML)没有显示抛出的实际异常,只覆盖了哪些行(因此为什么OP知道要问这个问题)...... – ircmaxell 2010-08-12 18:09:30

+0

确实有一个例外。当单元测试没有$ _SERVER ['SERVER_NAME'];谢谢! – tom 2010-08-12 19:57:50

相关问题