r/PHPhelp • • 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

4 comments sorted by

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.

<?php

class myTest extends PHPUnit\Framework\TestCase {
	function testA():void {
		$this->expectException(InvalidArgumentException::class);

		$this->assertException('My Error A', myFunction(100, 50), 'My Error Message);
	}
}