我想在PHP7中测试标量类型提示和严格类型的示例方法。当我没有通过参数时,该方法应抛出TypeError
。 PHPSpec返回致命错误:
未捕获的TypeError:参数1传递给Example :: test
<?php
class Example
{
public function test(string $name)
{
$this->name = $name;
}
}
class ExampleSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('Test\Example');
}
function it_check_test_method_when_not_pass_argument()
{
$this->shouldThrow('\TypeError')->during('test');
}
}
一开始我宣布:declare(strict_types=1);
有什么问题?如何测试投掷TypeError
?
答案 0 :(得分:6)
经过进一步调查,这是一个PHPSpec错误,并已报告Jsfiddle。该漏洞在几个月内没有修复,因此我建议对其进行评论。
如果您查看here中的代码,可以看到PHPSpec捕获了继承&#39; Exception
&#39;然后检查该异常的实例类型。但是,Error
并非从Exception
继承,而是从Throwable
继承。它与101 public function verifyPositive($callable, array $arguments, $exception = null)
102 {
103 try {
104 call_user_func_array($callable, $arguments);
105 } catch (\Exception $e) {
106 if (null === $exception) {
107 return;
108 }
109
110 if (!$e instanceof $exception) {
111 throw new FailureException(sprintf(
112 'Expected exception of class %s, but got %s.',
113 $this->presenter->presentValue($exception),
114 $this->presenter->presentValue($e)
115 ));
116 }
的唯一共同点是它们都实现了TypeError
接口。
例如:
function slugify(text){
return text.toString().toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\u0100-\uFFFF\w\-]/g,'-') // Remove all non-word chars ( fix for UTF-8 chars )
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
}
报告错误,解释这些详情,并向他们展示src/PhpSpec/Matcher/ThrowMatcher.php
有关Barack_Obama Барак_Обама ~!@#$%^&*()+/-+?><:";'{}[]\|`
的继承。
答案 1 :(得分:5)
对我来说,如果我用这个注释单元测试它是有效的:
/**
* @expectedException \TypeError
*/
然后我的测试是绿色的。