PHP SimpleTest Unit Testing – Expecting Exceptions and Errors

Like a good programmer, I try to be good about unit testing More Info. And also as a good programmer, I throw errors in my PHP where appropriate. I just learned today after a bit of digging through the codebase, that SimpleTest can be told to expect an Exception (or error) to be thrown in the test.

When using trigger_error(), you can use the expectError() as follows:

$this->expectError( $errorMessageToExpect, 'My message about this test case' );

Note that there is an internal queue of errors in SimpleTest, so it will expect precisely one error for each call to expectError().

If, however, you’re using throw you use expectException instead:

$this->expectException( $exceptionclass, 'My message about this test case' );

You can specify the class of exception to expect in the first parameter – the usual type would be Exception, of course. If you set the first parameter to false, it defaults to this type.