r/PHPhelp • u/trymeouteh • Oct 03 '25
PHPUnit: Assertion message for exceptions
When using $this->assertSame(); or any assertion method, the last parameter is the message that is displayed if the assertion fails.
Is it possible to use assertions on thrown exceptions and set an error message for the failed assertions? Currently I have each exception test inside a different test method but if possible I would like to have all the exception tests all be in one test method.
<?php
class myTest extends PHPUnit\Framework\TestCase {
function testA():void {
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('My Error A');
myFunction(100, 50);
}
function testB():void {
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('My Error B');
myFunction(50, -100);
}
}
1
Upvotes
View all comments
Show parent comment
1
u/trymeouteh Oct 05 '25
I would prefer this if possible. But if this cannot be done, I can live without it.