28 lines
973 B
Plaintext
28 lines
973 B
Plaintext
![]() |
In PHPUnit, to test that an exception is thrown in a given piece of code, the _expectException*()_ methods or the _@expectedException*_ annotations can be used. For such a test to succeed, something in the test method has to throw an exception with the awaited properties. Having an assertion at the end of such a test method, means that, if the test succeeds, that assertion was never evaluated because an exception was thrown before getting to that point.
|
||
|
|
||
|
== Noncompliant Code Example
|
||
|
|
||
|
----
|
||
|
public function testA() {
|
||
|
$o = new MyClass();
|
||
|
$this->expectException(\Exception::class);
|
||
|
$o->doSomething();
|
||
|
$this->assertTrue($o->hasProperty()); // Noncompliant - This assertion might never get evaluated
|
||
|
}
|
||
|
----
|
||
|
|
||
|
== Compliant Solution
|
||
|
|
||
|
----
|
||
|
public function testA() {
|
||
|
$o = new MyClass();
|
||
|
$this->expectException(\Exception::class);
|
||
|
$o->doSomething();
|
||
|
}
|
||
|
|
||
|
public function testB() {
|
||
|
$o = new MyClass();
|
||
|
$this->assertTrue($o->hasProperty());
|
||
|
}
|
||
|
----
|