使用 phpunit 测试 PHP 解析错误
Testing PHP parse errors with phpunit
我需要测试我们的错误记录器在各种情况下的工作方式。一种这样的情况是解析错误。这是一个例子:
public function testParseErrorLogsAnError()
{
$this->assertCount(0, $this->log_handler->getRecords());
try {
eval('<?php not good');
$this->fail('Code above should throw a parse error');
} catch (\Exception $e) {
$this->assertInstanceOf(\ParseError::class, $e);
}
$this->assertCount(1, $this->log_handler->getRecords());
}
问题是 phpunit 总是存在异常,永远不会进入 catch
块。如何禁用或覆盖 phpunit 的异常处理程序,以便我们可以测试自己的异常处理程序?
对于这个答案,我假设您使用的是 PHP 7。在 PHP 5 中,无法捕获解析错误并且将始终终止您的 PHP 进程。
在 PHP 7 中,您 可以 使用 try/catch 语句捕获解析错误(与另一个答案说)。但是,PHP 7 的 ParseError
class 扩展了 Error
class,而不是 Exception
(另见 documentation)。所以 catch (\Exception $e)
将不起作用,但其中任何一个都应该:
catch (\ParseError $e) { ...
catch (\Error $e) { ...
catch (\Throwable $e) { ...
或者,使用@DevDonkey 已经建议的 @expectedException
注释:
/**
* @expectedException ParseError
*/
public function testParseErrorLogsAnError()
{
eval('<?php not good');
}
我需要测试我们的错误记录器在各种情况下的工作方式。一种这样的情况是解析错误。这是一个例子:
public function testParseErrorLogsAnError()
{
$this->assertCount(0, $this->log_handler->getRecords());
try {
eval('<?php not good');
$this->fail('Code above should throw a parse error');
} catch (\Exception $e) {
$this->assertInstanceOf(\ParseError::class, $e);
}
$this->assertCount(1, $this->log_handler->getRecords());
}
问题是 phpunit 总是存在异常,永远不会进入 catch
块。如何禁用或覆盖 phpunit 的异常处理程序,以便我们可以测试自己的异常处理程序?
对于这个答案,我假设您使用的是 PHP 7。在 PHP 5 中,无法捕获解析错误并且将始终终止您的 PHP 进程。
在 PHP 7 中,您 可以 使用 try/catch 语句捕获解析错误(与另一个答案说)。但是,PHP 7 的 ParseError
class 扩展了 Error
class,而不是 Exception
(另见 documentation)。所以 catch (\Exception $e)
将不起作用,但其中任何一个都应该:
catch (\ParseError $e) { ...
catch (\Error $e) { ...
catch (\Throwable $e) { ...
或者,使用@DevDonkey 已经建议的 @expectedException
注释:
/**
* @expectedException ParseError
*/
public function testParseErrorLogsAnError()
{
eval('<?php not good');
}