我用自己的扩展了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将输出:
我想要:
如何扩展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
执行并输出:
最佳答案
我不确定这是否是最佳选择,但是您可以实现测试结果打印机,例如:
<?php
namespace Tests;
use PHPUnit\TextUI\ResultPrinter;
class TestPrinter extends ResultPrinter
{
protected function printDefect(\PHPUnit\Framework\TestFailure $defect, $count)
{
$this->printDefectHeader($defect, $count);
$ex = $defect->thrownException();
// you can do whatever you need here,
// like check exception type, etc,
// printing just line number here
$this->write('Line #' . $ex->getLine() . "\n");
$this->printDefectTrace($defect);
}
}
并注册为要使用的打印机(假定为xml配置,但也可以通过命令行完成):
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.1/phpunit.xsd"
backupGlobals="false"
colors="true"
bootstrap="vendor/autoload.php"
printerClass="Tests\TestPrinter"
>
<!-- note printerClass attribute above -->
</phpunit>
这样做,您将获得与以下内容类似的输出:
There was 1 error:
1) Tests\SomeTest::testStuff
Line #16
LogicException: whatever
(我只是做了一个简单的测试
throw new \LogicException('whatever');
)