那么是这样的对于expectException在phpunit中这个用法之前我也不甚了解,当时就暂时没有纠结了,暂时先放下,看了官方文档后面的部分后再次回来看就豁然开朗了。
它这里主要是这样的意思就是说在expectException方法中传入一个异常的类型(参数值为string)这里假定这个异常类型是a,那么在接下来的语句中如果有throw new a(‘a异常’)像是这样的,则可以算做是expectException断言抛出异常a为正确的断言。
那么实例如:
ExceptionTest.php:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ExceptionTest extends TestCase
{
public function testException(): void
{
$this->expectException(InvalidArgumentException::class);
throw new InvalidArgumentException("无效参数异常");
}
}
这里断言了testException方法中会有无效参数异常抛出,那么然后就紧接着抛出了无效参数异常。
那么运行效果:
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\ExceptionTest.php
PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)
Time: 00:00.004, Memory: 20.00 MB
OK (1 test, 1 assertion)
自然是断言成功。
那你比如说这里抛出的异常类型不用InvalidArgumentException而是直接抛出Exception:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ExceptionTest extends TestCase
{
public function testException(): void
{
$this->expectException(InvalidArgumentException::class);
throw new Exception("exception异常");
}
}
则运行结果:
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\ExceptionTest.php
PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
F 1 / 1 (100%)
Time: 00:00.005, Memory: 20.00 MB
There was 1 failure:
1) ExceptionTest::testException
Failed asserting that exception of type "Exception" matches expected exception "InvalidArgumentException". Message was: "exception异常" at
C:\Users\Administrator\PhpstormProjects\untitled\ExceptionTest.php:9
.
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
这样肯定就是说断言失败了。断言和实际抛出的异常是不同的。