rspec/rules/S5935/php/rule.adoc

47 lines
1.1 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
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
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,php]
2021-04-28 16:49:39 +02:00
----
public function testA()
{
try {
doSomething();
$this->fail("Assertion should have been thrown");
} catch (MyException $e) {
assertEquals("Exception message", $e->getMessage());
}
}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,php]
2021-04-28 16:49:39 +02:00
----
public function testB()
{
$this->expectException(MyException::class);
$this->expectExceptionMessage("Exception message");
doSomething();
}
----
== Resources
2021-04-28 16:49:39 +02:00
thePHP.cc: https://thephp.cc/articles/questioning-phpunit-best-practices[Questioning PHPUnit Best Practice]