默認(rèn)情況下,PHPUnit 將測試在執(zhí)行中觸發(fā)的 PHP 錯(cuò)誤、警告、通知都轉(zhuǎn)換為異常。先不說其他好處,這樣就可以預(yù)期在測試中會(huì)觸發(fā) PHP 錯(cuò)誤、警告或通知,如示例 2.12 所示。
注解:
PHP 的error_reporting
?運(yùn)行時(shí)配置會(huì)對(duì) PHPUnit 將哪些錯(cuò)誤轉(zhuǎn)換為異常有所限制。如果在這個(gè)特性上碰到問題,請確認(rèn) PHP 的配置中沒有抑制你所關(guān)注的錯(cuò)誤類型。
示例 2.12 預(yù)期會(huì)出現(xiàn) PHP 錯(cuò)誤、警告和通知
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ErrorTest extends TestCase
{
public function testDeprecationCanBeExpected(): void
{
$this->expectDeprecation();
// (可選)測試訊息和某個(gè)字符串相等
$this->expectDeprecationMessage('foo');
// 或者(可選)測試訊息和某個(gè)正則表達(dá)式匹配
$this->expectDeprecationMessageMatches('/foo/');
\trigger_error('foo', \E_USER_DEPRECATED);
}
public function testNoticeCanBeExpected(): void
{
$this->expectNotice();
// (可選)測試訊息和某個(gè)字符串相等
$this->expectNoticeMessage('foo');
// 或者(可選)測試訊息和某個(gè)正則表達(dá)式匹配
$this->expectNoticeMessageMatches('/foo/');
\trigger_error('foo', \E_USER_NOTICE);
}
public function testWarningCanBeExpected(): void
{
$this->expectWarning();
// (可選)測試訊息和某個(gè)字符串相等
$this->expectWarningMessage('foo');
// 或者(可選)測試訊息和某個(gè)正則表達(dá)式匹配
$this->expectWarningMessageMatches('/foo/');
\trigger_error('foo', \E_USER_WARNING);
}
public function testErrorCanBeExpected(): void
{
$this->expectError();
// (可選)測試訊息和某個(gè)字符串相等
$this->expectErrorMessage('foo');
// 或者(可選)測試訊息和某個(gè)正則表達(dá)式匹配
$this->expectErrorMessageMatches('/foo/');
\trigger_error('foo', \E_USER_ERROR);
}
}
如果測試代碼使用了會(huì)觸發(fā)錯(cuò)誤的 PHP 內(nèi)建函數(shù),比如 ?fopen
?,有時(shí)候在測試中使用錯(cuò)誤抑制符會(huì)很有用。通過抑制住錯(cuò)誤通知,就能對(duì)返回值進(jìn)行檢查,否則錯(cuò)誤通知將會(huì)導(dǎo)致 PHPUnit 的錯(cuò)誤處理程序拋出異常。
示例 2.13 對(duì)會(huì)引發(fā)PHP 錯(cuò)誤的代碼的返回值進(jìn)行測試
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ErrorSuppressionTest extends TestCase
{
public function testFileWriting(): void
{
$writer = new FileWriter;
$this->assertFalse(@$writer->write('/is-not-writeable/file', 'stuff'));
}
}
final class FileWriter
{
public function write($file, $content)
{
$file = fopen($file, 'w');
if ($file === false) {
return false;
}
// ...
}
}
$ phpunit ErrorSuppressionTest
PHPUnit latest.0 by Sebastian Bergmann and contributors.
.
Time: 1 seconds, Memory: 5.25Mb
OK (1 test, 1 assertion)
如果不使用錯(cuò)誤抑制符,此測試將會(huì)失敗,并報(bào)告 ?fopen(/is-not-writeable/file): failed to open stream: No such file or directory
?
更多建議: