【发布时间】:2018-10-19 11:06:11
【问题描述】:
我正在尝试测试我的 CakePHP 3 内部错误异常。
我的控制器:
public function getConfirmation()
{
if (!$this->request->getData())
throw new InternalErrorException(__('data not found'));
$confirmStatus = $this->XYZ->getConfirmation($this->request->getData('ID'), $this->request->getData('MANAGER_ID'));
$this->set([
'confirmStatus' => ($confirmStatus) ? 1 : 0,
]);
}
在异常测试中,我按照Sebastian Bergmann's blog 的建议添加了expectException,我认为这是个好主意:
public function testInternalErrorExceptionIsRaised()
{
$this->enableCsrfToken();
$this->enableSecurityToken();
$formPostData = [];
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$this->expectException(\Cake\Network\Exception\InternalErrorException::class);
$this->post(
[
'controller' => 'XYZ',
'action' => 'getConfirmation'
],
$formPostData
);
$this->assertResponseFailure();
$this->assertResponseCode(500);
}
错误:
1) App\Test\TestCase\Controller\XYZControllerTest::testInternalErrorExceptionIsRaised
无法断言“Cake\Network\Exception\InternalErrorException”类型的异常被抛出。
我尝试了各种方法,但无法测试 CakePHP 3 异常。我也试过expectExceptionCode() 和expectExceptionMessage,但没有运气。是否可以测试异常?
【问题讨论】:
标签: unit-testing exception cakephp integration-testing cakephp-3.x