41 lines
1.2 KiB
Plaintext
41 lines
1.2 KiB
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
|
|
|
|
[source,php]
|
|
----
|
|
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
|
|
|
|
[source,php]
|
|
----
|
|
public function testA() {
|
|
$o = new MyClass();
|
|
$this->expectException(\Exception::class);
|
|
$o->doSomething();
|
|
}
|
|
|
|
public function testB() {
|
|
$o = new MyClass();
|
|
$this->assertTrue($o->hasProperty());
|
|
}
|
|
----
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::../message.adoc[]
|
|
|
|
include::../highlighting.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|