【发布时间】:2011-03-29 01:53:41
【问题描述】:
我正在使用 phpUnit 编写一些单元测试来测试 Zend Framework 应用程序,但在 changePassword 函数中测试异常时遇到了一些问题。测试没有失败,但在生成 html 的覆盖工具中,“throw new Exception($tr->translate('userOldPasswordIncorrect'));”线路未经过测试。
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 方法中使用一般异常。
【问题讨论】:
-
testFindByAuth 通过了吗?如果没有,depends 甚至不会让 testChangePasswordWrongOldPassword 运行。
标签: php unit-testing zend-framework phpunit