lundi 23 mars 2020

Why I get `Could not load mock MyClassConsumer, class already exists` once I test my phpUnit static methods that create the very same class?

I have the following class:


public function MyClass
{
  public static foo():string
  {
    // Some logic there
    // This is a dummy value just for explaining the problem
    return 'n123';
  }

  public static factory():MyClass
  {
    return new MyClass();
  }
}

Also I have the following class as well:


class MyClassConsumer
{
 public function bar()
 {
   $myclass=MyClass:factory();
   $myclass->foo();
 }
}

In my ClassConsumer also as recomended I did the following phpunit test:

use PHPUnit\Framework\TestCase;
use Mockery;
use MyClassConsumer;

class TestMyClassConsumer extends TestCase
{
  public function testBar()
  {
    $mockedFoo=Mockery:spy(MyClassConsumer::class);
    $mockedFoo->shouldReceive('foo')->andReturn('n1111');

    $mockedFactory=Mockery:mock('alias:'.MyClassConsumer::class);
    $mockedFactory->shouldReceive('factory')->andReturn($mockedFoo);

    $classConsumer=new ClassConsumer();
    $classConsumer->bar();
    $mockedFoo->shouldHaveReceived('foo');
  }
}

But Once I test it I get the following error:

There was 1 error:

1) TestMyClassConsumer::testBar
Mockery\Exception\RuntimeException: Could not load mock MyClassConsumer, class already exists

/var/www/html/vendor/mockery/mockery/library/Mockery/Container.php:226
/var/www/html/vendor/mockery/mockery/library/Mockery.php:118
/var/www/html/tests/TestMyClassConsumer.php:30

ERRORS!
Tests: 1, Assertions: 2, Errors: 1.

Do you know the reason why this error ocurs and how I can fix it?

Aucun commentaire:

Enregistrer un commentaire