Phpunit中expectDeprecation方法用来断言一个错误,一个废弃或者过去的不赞成的方法等的错误。
一个具体的实例:ErrorTest.php:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ErrorTest extends TestCase
{
public function testDeprecationCanBeExpected(): void
{
$this->expectDeprecation();
\trigger_error('foo', \E_USER_DEPRECATED);
}
}
这里进行了会触发一个Deprecation错误的断言,然后接着就用户自定义了一个Deprecation错误抛出,则正好应了这个Deprecation错误的断言。
那么运行结果:
C:\Users\Administrator>D:\phpstudy_pro\Extensions\php\php7.3.4nts\php.exe D:\phpstudy_pro\Extensions\php\php7.3.4nts\phpunit-9.5.8.phar C:\Users\Administrator\PhpstormProjects\untitled\ErrorTest.php
PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)
Time: 00:00.002, Memory: 20.00 MB
OK (1 test, 1 assertion)
可见自然是ok的。
那么像是这样:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ErrorTest extends TestCase
{
public function testDeprecationCanBeExpected(): void
{
$this->expectDeprecation();
//\trigger_error('foo', \E_USER_DEPRECATED);
}
}
我将用户自定义抛出的Deprecation错误给注释掉,然后重新运行:
C:\Users\Administrator>D:\phpstudy_pro\Extensions\php\php7.3.4nts\php.exe D:\phpstudy_pro\Extensions\php\php7.3.4nts\phpunit-9.5.8.phar C:\Users\Administrator\PhpstormProjects\untitled\ErrorTest.php
PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
F 1 / 1 (100%)
Time: 00:00.004, Memory: 20.00 MB
There was 1 failure:
1) ErrorTest::testDeprecationCanBeExpected
Failed asserting that exception of type "PHPUnit\Framework\Error\Deprecated" is thrown.
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
那么自然是会发生错了,因为你断言会产生Deprecation错误,而实际上并没有产生Deprecation错误。