47 lines
1.1 KiB
Plaintext
47 lines
1.1 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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
|
|
|
|
[source,php]
|
|
----
|
|
public function testA()
|
|
{
|
|
try {
|
|
doSomething();
|
|
$this->fail("Assertion should have been thrown");
|
|
} catch (MyException $e) {
|
|
assertEquals("Exception message", $e->getMessage());
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,php]
|
|
----
|
|
public function testB()
|
|
{
|
|
$this->expectException(MyException::class);
|
|
$this->expectExceptionMessage("Exception message");
|
|
|
|
doSomething();
|
|
}
|
|
----
|
|
|
|
|
|
== Resources
|
|
|
|
thePHP.cc: https://thephp.cc/articles/questioning-phpunit-best-practices[Questioning PHPUnit Best Practice]
|
|
|