代码之家  ›  专栏  ›  技术社区  ›  Matrix12

PHP7中的PHPSpec捕获类型错误

  •  8
  • Matrix12  · 技术社区  · 9 年前

    我想在PHP7中用标量类型提示和严格类型测试一个示例方法 TypeError .PHPSpec返回致命错误:

    未捕获类型错误:参数1传递给示例::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);

    怎么了?如何测试投掷 类型错误 ?

    2 回复  |  直到 9 年前
        1
  •  6
  •   Calamity Jane    7 年前

    对我来说,如果我用以下内容注释单元测试,它会起作用:

    /**
     * @expectedException \TypeError
     */
    

    那么我的测试是绿色的。

        2
  •  6
  •   Will Brian Hodge    9 年前

    经进一步调查,这是一个PHPSpec错误,已报告 here 。这个bug已经几个月没有修复了,所以我建议对它进行评论。

    如果您查看中的代码 src/PhpSpec/Matcher/ThrowMatcher.php ,您可以看到PHPSpec捕获继承“ Exception ',然后检查该异常的实例类型。但是 TypeError 不继承自 例外 ,它继承自 Error 。它唯一的共同点是 例外 ,是因为他们都实现了 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             }
    

    报告错误,解释这些细节,并展示它们 this documentation 关于 类型错误 .