sebastianbergmann / phpunit-mock-objects

Mock Object library for PHPUnit
https://phpunit.de/
Other
4.98k stars 154 forks source link

Mocking class that contains a method with 'iterable' return type #384

Closed andaniel05 closed 6 years ago

andaniel05 commented 6 years ago

PHP Fatal error: Cannot use 'iterable' as class name as it is reserved in phar://xxxxxxxx/phpunit-6.4.3.phar/phpunit-mock-objects/Generator.php(263) : eval()'d code on line 1

<?php

use PHPUnit\Framework\TestCase;

class Foo
{
    public function traverse(): iterable
    {
        $gen = function () {
            yield 1;
            yield 2;
            return 3;
        };

        return $gen();
    }
}

class Bar
{
    public function run(Foo $foo)
    {
        $foo->traverse();
    }
}

class AppTest extends TestCase
{
    public function test()
    {
        $fooStub = $this->createMock(Foo::class);

        $bar = new Bar;
        $bar->run($fooStub);
    }
}
sebastianbergmann commented 6 years ago

Does this solve your problem?

diff --git a/src/Invocation/Static.php b/src/Invocation/Static.php
index b3734b5..9406e23 100644
--- a/src/Invocation/Static.php
+++ b/src/Invocation/Static.php
@@ -124,7 +124,7 @@ public function toString()
      */
     public function generateReturnValue()
     {
-        switch ($this->returnType) {
+        switch (strtolower($this->returnType)) {
             case '':       return;
             case 'string': return $this->returnTypeNullable ? null : '';
             case 'float':  return $this->returnTypeNullable ? null : 0.0;
@@ -134,12 +134,13 @@ public function generateReturnValue()
             case 'void':   return;

             case 'callable':
-            case 'Closure':
+            case 'closure':
                 return function () {
                 };

-            case 'Traversable':
-            case 'Generator':
+            case 'traversable':
+            case 'generator':
+            case 'iterable':
                 $generator = function () {
                     yield;
                 };
andaniel05 commented 6 years ago

Hi Sebastian. Sorry for my delayed response. Now this solve my issue. Thanks.