0

I need to test how our error logger works in various scenarios. One such scenario are parse errors. Here's an example:

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());
}

Problem is that phpunit always exists with an exception, and never enters catch block. How to disable or orverride phpunit's exception handler, so we can test our own?

1
  • An exception being thrown is a PHP7 feature of eval. Are you using PHP7? Commented Apr 14, 2016 at 13:12

1 Answer 1

2

For this answer, I'm assuming you're using PHP 7. In PHP 5, Parse Errors cannot be caught and will always terminate your PHP process.

In PHP 7, you can catch Parse Errors using a try/catch statement (contrary to what the other answer says). However, PHP 7's ParseError class extends the Error class, not Exception (see also the documentation). So catch (\Exception $e) will not work, but any of these should:

catch (\ParseError $e) { ...
catch (\Error $e) { ...
catch (\Throwable $e) { ...

Alternatively, use the @expectedException annotation als already suggested by @DevDonkey:

/**
 * @expectedException ParseError
 */
public function testParseErrorLogsAnError()
{
    eval('<?php not good');
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.