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 04 '25
By message I am referring to the last parameter in any of the asset methods
$this->assertSame(a, b, 'my message');. Instead of having a desperate method for each exception test, I would like to have all of the exceptions in one method and use an assert method with a message parameter to give the assertion a name.