使用phpunit测试PHP解析错误

时间:2016-04-14 13:07:59

标签: php testing 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的异常处理程序,以便我们可以测试自己的?

1 个答案:

答案 0 :(得分:2)

对于这个答案,我假设您正在使用PHP 7.在PHP 5中,无法捕获解析错误,并且将始终终止您的PHP进程。

在PHP 7中,可以使用 try / catch 语句捕获解析错误(与其他答案所说的相反)。但是,PHP 7的#!/bin/sh # Output colors red='\033[0;31m'; green='\033[0;32m'; yellow='\033[0;33m'; default='\033[0;m'; # personal touch :-) echo "${red}" echo " " echo " |ZZzzz " echo " | " echo " | " echo " |ZZzzz /^\ |ZZzzz " echo " | |~~~| | " echo " | |- -| / \ " echo " /^\ |[]+ | |^^^| " echo " |^^^^^^^| | +[]| | | " echo " | +[]|/\/\/\/\^/\/\/\/\/|^^^^^^^| " echo " |+[]+ |~~~~~~~~~~~~~~~~~~| +[]| " echo " | | [] /^\ [] |+[]+ | " echo " | +[]+| [] || || [] | +[]+| " echo " |[]+ | || || |[]+ | " echo " |_______|------------------|_______| " echo " " echo " " echo "${default}" echo "You have just checked out branch :-)" exit 0; 类扩展了ParseError类,而不是Error(另请参阅documentation)。所以Exception不起作用,但其中任何一个都应该:

catch (\Exception $e)

或者,使用@DevDonkey已经建议的catch (\ParseError $e) { ... catch (\Error $e) { ... catch (\Throwable $e) { ... 注释:

@expectedException