PHPSpec Catching TypeError in PHP7

I want to test an example method with a scalar type and strong types in PHP7. When I do not pass an argument, the method should throw a TypeError . PHPSpec returns a fatal error:

Uncaught TypeError: argument 1 passed to 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'); } } 

In the beginning I declare: declare(strict_types=1);

What's wrong? How to check throwing TypeError ?

+7
php tdd php-7 phpspec
source share
2 answers

For me, this works if I annotate the unit test as follows:

 /** * @expectedException \TypeError */ 

Then my test is green.

+3
source share

Upon further investigation, this is a PHPSpec error, and was reported here . The error was not fixed after a few months, so I would suggest commenting on it.

If you look at the code in src/PhpSpec/Matcher/ThrowMatcher.php , you will see that PHPSpec catches Exceptions that inherit ' Exception ', and then checks the instance type of this exception. But TypeError does not inherit from Exception , it inherits from Error . The only thing he has with Exception is that they implement the Throwable interface.

For example:

 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 } 

Report a bug, explain these details, and show them this documentation of TypeError inheritance.

+5
source share

All Articles