我试图验证php7函数只接受整数.
这是班级:
<?php
declare(strict_types=1);
class Post
{
private $id;
public function setId(int $id)
{
$this->id = $id;
}
}
Run Code Online (Sandbox Code Playgroud)
这是测试:
<?php
declare(strict_types=1);
class PostTest extends \PHPUnit_Framework_TestCase
{
private function getPostEntity()
{
return new Post();
}
public function testSetId()
{
$valuesExpected = [123, '123a'];
foreach ($valuesExpected as $input) {
$this->getPostEntity()->setId($input);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
TypeError: Argument 1 passed to Post::setId() must be of the type integer, string given, called in /path/test/PostTest.php on line 35
有可能验证这样的错误吗?还有,运行这样的支票是否有意义?
可悲的是,TypeError 它不是Exception(参考)的子类,而是它的延伸Error.他们唯一真正分享的是Throwable界面.ThrowMatcher实际上无法捕获TypeError.
如果查看代码
src/PhpSpec/Matcher/ThrowMatcher.php,可以看到PHPSpec捕获继承'Exception'的异常,然后检查该异常的实例类型.
另见这个答案.
| 归档时间: |
|
| 查看次数: |
4526 次 |
| 最近记录: |