PHPUnit provides helper functions and annotations to verify that a given block of code throws an exception and to assert different properties of
that exception. The provided helper functions are:
-
expectException()
-
expectExceptionCode()
-
expectExceptionMessage()
-
expectExceptionMessageRegExp()
This check raises an issue when the throw of an exception is verified using a try-catch approach instead of relying on the provided helper
functions.
Noncompliant code example
public function testA()
{
try {
doSomething();
$this->fail("Assertion should have been thrown");
} catch (MyException $e) {
assertEquals("Exception message", $e->getMessage());
}
}
Compliant solution
public function testB()
{
$this->expectException(MyException::class);
$this->expectExceptionMessage("Exception message");
doSomething();
}