expectDeprecationMessage在phpunit中相比于expectDeprecation则断言更加精准些,expectDeprecation只是断言会触发一个DEPRECATED错误,但是具体错误的消息是什么并没有精准的断言。
那么expectDeprecationMessage则可以直接断言到具体的DEPRECATED错误消息(是否包含这个具体错误)。
但是expectDeprecationMessage使用的前提是必须先执行expectDeprecation方法。
实例如:ErrorTest.php:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ErrorTest extends TestCase
{
public function testDeprecationCanBeExpected(): void
{
$this->expectDeprecation();
$this->expectDeprecationMessage('foo');
\trigger_error('fool', \E_USER_DEPRECATED);
}
}
这里断言DEPRECATED错误消息中有包含foo字串。那么接下来就触发了DEPRECATED错误,并且错误消息为fool。那么这样的断言自然是成立的。
运行结果如:
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.004, Memory: 20.00 MB
OK (1 test, 2 assertions)
那么像是如果将fool修改为xxx,触发的DEPRECATED错误消息内容自然就不是包含foo字串的断言了。
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ErrorTest extends TestCase
{
public function testDeprecationCanBeExpected(): void
{
$this->expectDeprecation();
$this->expectDeprecationMessage('foo');
\trigger_error('xxx', \E_USER_DEPRECATED);
}
}
运行结果:
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 message 'xxx' contains 'foo'.
FAILURES!
Tests: 1, Assertions: 2, Failures: 1.
果然运行结果就没有通过断言测试。