Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make phpunit catch php7 TypeError

Tags:

php-7

phpunit

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?

like image 947
michaelbn Avatar asked Dec 18 '15 07:12

michaelbn


2 Answers

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.

like image 60
Sebastian Bergmann Avatar answered Oct 22 '22 08:10

Sebastian Bergmann


Try this:

$this->expectException(TypeError::class);
like image 23
Синкевич Алексей Avatar answered Oct 22 '22 09:10

Синкевич Алексей