Skip to content

Conversation

@VincentLanglet
Copy link
Contributor

  • expectException works with a Throwable class and is typed class-string<Throwable>
  • Throwable has both Message and Code

So this method could works on Throwable.

@staabm
Copy link
Contributor

staabm commented Oct 16, 2025

Do you have a real world use-case in mind?

@VincentLanglet
Copy link
Contributor Author

Do you have a real world use-case in mind?

Sure, multiple.

Let's say I have a test with something like

$this->someSubService
            ->expects($this->once())
            ->method('execute')
            ->willThrowException($thrownException);

if (null !== $expectedException) {
     $this->expectExceptionObject($expectedException);
}
$this->myHandler->__invoke($message);

I'm restricted to the typehint

public function testThrowException(\Throwable $thrownException, ?\Exception $expectedException): void

because even if the Throwable is accepted by willThrowException it is not by expectExceptionObject.

For the same reason, I cannot do expectation on Error, like TypeError, ValueError, and so on while I can configure my mock to throw one.

I can still use expectException which supports Throwable, and combine it with expectExceptionMessage.
But I don't see a reason to not support it in expectExceptionObject too then.

@sebastianbergmann
Copy link
Owner

I cannot do expectation on Error, like TypeError, ValueError, and so on while I can configure my mock to throw one.

To me, that is not a valid argument, because expecting PHP errors such as 'TypeError' does not make sense, at least not to me. I do see the asymmetry between willThrowException() and expectExceptionObject(), though.

@sebastianbergmann sebastianbergmann merged commit f2e9a64 into sebastianbergmann:12.5 Oct 22, 2025
31 checks passed
@sebastianbergmann sebastianbergmann changed the title Allow Throwable in expectExceptionObject Allow Throwable in expectExceptionObject() Oct 22, 2025
@sebastianbergmann sebastianbergmann added type/enhancement A new idea that should be implemented feature/assertion Issues related to assertions and expectations labels Oct 22, 2025
@sebastianbergmann sebastianbergmann added this to the PHPUnit 12.5 milestone Oct 22, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature/assertion Issues related to assertions and expectations type/enhancement A new idea that should be implemented

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants