大佬教程收集整理的这篇文章主要介绍了没有用phpUnit测试异常?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在用PHPUnit编写一些单元测试来测试Zend Framework应用程序,并且在changepassword函数中测试异常时遇到了一些问题.测试不会失败,但是会在生成html的覆盖率工具中“抛出新的异常($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方法中使用一般的Exception.
解决方法:
我猜?从PC_Translate_MysqL :: geTinstance()引发了异常.
这就是使用单个Exception的麻烦.这使得检查抛出什么异常变得更加困难.我建议更改changepassword方法以引发其他异常.可能是InvalidArgumentexception或RuntimeException.然后测试那个.
出于这个原因,我个人一直使用自定义异常.
try {
} catch (DatabaseQueryException $E) {
// Handle database error
} catch (DatabaseConnectionException $E) {
// We never even connected...
} catch (InvalidArgumentexception $E) {
//...
}
通常,出于这个原因,我永远不要使用catch(Exception $E).您永远不知道自己捕获了什么异常. (我确实定义了一个自定义的异常处理程序,因此,如果应用程序未捕获,则不会致命.而是显示500错误并记录异常).
以上是大佬教程为你收集整理的没有用phpUnit测试异常?全部内容,希望文章能够帮你解决没有用phpUnit测试异常?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。