Mar 3rd, 2013
When you're using phpunit to test for an exception you can use $this->setExpectedException()
or the annotation for setting up your test to listen to the exception. If the expected exception is not thrown your test will fail and phpunit will report the issue. In most test cases this works very well. But sometimes you might want test the content of the exception message. For example if it contains some debug infos. Of course you could use $this->setExpectedExceptionMessage()
, but you would have to fill in the whole literal exception message. When someone is correcting a typo in the exception message your test will fail (but the exception is still thrown correctly).
You could assert that the exception is thrown when you write the whole test by hand like this:
public function testAnExceptionIsThrownWithDebugInfo_version1() {
try {
$this->start();
} catch (SerienLoader\Exception $e) {
$this->assertContains('some debug info', $e->getMessage());
return;
}
$this->fail('Expected Exception is not thrown');
}
But I think this is a little bit to verbose and difficult to read. And if you're forgetting to return in the catch clause your test will report really weird things. Looking closer at it, you will get only one assertion into your assertion log (assertContains) when the test is passed. But actually you're for two things in one test: a) the correct exception and b) the message contains the debug info.
public function testAnExceptionIsThrownWithDebugInfo_version2() {
$this->setExpectedException('SerienLoader\Exception');
try {
$this->start();
} catch (SerienLoader\Exception $e) {
$this->assertContains('some debug info', $e->getMessage());
throw $e;
}
}
Testing the exception like this has some advantages: