Make phpunit catch php7 TypeError

…衆ロ難τιáo~ 提交于 2020-11-30 09:14:50

问题


I am trying to validate that a php7 function accept only integers.

This is the class:

<?php

declare(strict_types=1);

class Post
{
    private $id;

    public function setId(int $id)
    {
        $this->id = $id;
    }
}

And this is the test:

<?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);
        }
    }
}

The error I get is:

TypeError: Argument 1 passed to Post::setId() must be of the type integer, string given, called in /path/test/PostTest.php on line 35

Is it possible to validate such error? also, does it make any sense to run such a check?


回答1:


Yes, you can test for TypeError the same way you would use for any other exception.

However, I would not test that PHP emits a type error in case of a type mismatch. This is the kind of test that becomes superfluous with PHP 7 code.




回答2:


Try this:

$this->expectException(TypeError::class);



回答3:


Sadly, TypeError is not a subclass of Exception (reference), whilst it extends Error. The only thing they are really sharing is the the Throwable interface. The ThrowMatcher can't actually catch a TypeError.

If you look at the code in src/PhpSpec/Matcher/ThrowMatcher.php, you can see that PHPSpec catches Exceptions that inherit 'Exception' and then checks the instance type of that exception.

See also this answer.




回答4:


For newer PHP versions try:

$this->expectError(TypeError::class);


来源:https://stackoverflow.com/questions/34350734/make-phpunit-catch-php7-typeerror

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!