phptddphp-7phpspec

PHPSpec Catching TypeError in PHP7


I want test an example method with scalar type hinting and strict types in PHP7. When I don't pass an argument, the method should throw a TypeError. PHPSpec return 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');
    }
}

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

What is wrong? How do I test throwing TypeError?


Solution

  • For me it works if I annotate the unit test with this:

    /**
     * @expectedException \TypeError
     */
    

    Then my test is green.