/contrib/famzah

Enthusiasm never stops

Testing exception message with PHPUnit

2 Comments

PHPUnit has a built-in method to test if an expected exception occurred during a test case:

$this->setExpectedException('Exception');

You cannot however test the message of the exception. There are cases where a program may throw the same exception type, but with different messages for different errors, and you want to differentiate between them.

Here is my example code on how to reliably test for the type and message of an exception:

class staticSessionTest extends PHPUnit_Framework_TestCase {
	...
	function test_bad_data() {
		$emess = null;
		try {
			$this->sess->start('must be array', FALSE, FALSE); # we expect an Exception here
		} catch (Exception $e) { $emess = $e->getMessage(); }
		$this->assertEquals($emess, 'Session data must be an array');
	}
	...
}

Putting the assertEquals() outside of the try…catch block ensures that you cannot forget to test for the message. The type of the exception is coded inside the catch(…) block.


UPDATE: I just re-read the latest PHPUnit Annotations, and this feature is already included in the standard PHPUnit suite. The difference between my custom code and the “@expectedExceptionMessage” annotation is that the annotation is valid for the whole test block of execution, while using try…catch you can specify precisely where you expect the exception to occur.


References:

Advertisements

Author: Ivan Zahariev

An experienced Linux & IT enthusiast, Engineer by heart, Systems architect & developer.

2 thoughts on “Testing exception message with PHPUnit

  1. Your article helped me avoid writing extra code.
    @expectedExceptionMessage annotation came handy and helped a lot.
    Thanks for the artilce.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s