我已经用我自己的扩展了 PHP Exception 来添加额外的数据:
class MyException extends Exception {
public $foo = [];
public function __construct($message = '', $data = null, $code = 0) {
$this->foo = $data;
paret::__construct($message, $code);
}
}
在执行正常请求时,这些错误会正确记录,我不想在$this->message.
运行测试时,我可以抛出它:
if (!$this->save()) {
throw new MyException('Internal Server Error', ['log' => 'missing data'], 500);
}
PHPUnit 将输出:
MyException:内部服务器错误
我想要:
MyExeption:内部服务器错误;{“日志”:“缺失数据”}
如何扩展 PHPUnit 以能够$myException->foo与错误消息一起显示?
示例代码:
<?php
class SampleTest extends CTestCase
{
public function testIndex()
{
$this->assertTrue($this->save());
}
protected function save()
{
$model = new Orders();
$model->addError('id', 'ID is Required');
if (!$model->validate()) {
throw new HttpApiModelException(500, 'Failed to save', $model);
}
return true;
}
}
用命令执行 common/vendor/bin/phpunit --configuration tests/phpunit.xml --verbose tests/functional/SampleTest.php
和输出:
aluckdog
呼如林