Skip to content

Proposal: Accessing Thrown Exceptions #5900

Closed
@cheack

Description

@cheack

We use custom exceptions in our application, each of which has a method public function isIgnored(): bool.
Currently, we have to use this approach:

try {
    $do->something();
    $this->fail('something() should throw Exception.');
} catch (Exception $e) {
    $this->assertEquals('message', $e->getMessage());
    $this->assertTrue($e->isIgnored());
}

Proposing:

I propose enhancing PHPUnit by introducing a mechanism to store the thrown exception during test execution. This could be achieved by modifying the runTest method to capture exceptions:

final protected function runTest(): mixed
{
    try {
        $testResult = $this->{$this->methodName}(...$testArguments);
    } catch (Throwable $exception) {
        ...
        // Something like this:
        $this->observedException = $exception;
        ...
    }

    return $testResult;
}

Subsequently, we could utilize the stored observedException in tearDown or other relevant methods for further assertions or checks.

This will allowed us to use an expressive way to define expectations:

$this->expectException(Exception::class);
$this->expectExceptionMessage('message');
$this->expectExceptionIsIgnored();

$do->something();

Metadata

Metadata

Assignees

No one assigned

    Labels

    type/enhancementA new idea that should be implemented

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions