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?
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.
Try this:
$this->expectException(TypeError::class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With