Mockery exception: could not load mock class already exists

Mockery\Exception\RuntimeException: Could not load mock , class already exists

When working with those spaghetti legacy code base, sometimes, it is fucking hard to write the test along with refactoring. We may face with some situation that need to mock the public static function call.

And the test class:

We use mockery to mock the static function call, run the test with single function, it’s green.
But, if we run the whole test case, it will throw:

So, to deal with this exception, add these annotation runInSeparateProcess preserveGlobalState

BAAM, it’s will green again if we run whole test case. Those 2 annotation will help mockery get rid of duplicating instance of Utils class (in this context)

These are some references from the phpunit document:

https://phpunit.de/manual/current/en/appendixes.annotations.html#appendixes.annotations.runInSeparateProcess

https://phpunit.de/manual/current/en/appendixes.annotations.html#appendixes.annotations.preserveGlobalState

4 thoughts on “Mockery exception: could not load mock class already exists”

  1. Didn’t work for me

    Mockery\Exception\RuntimeException: Could not load mock \MongoDB\Driver\Manager, class already exists

    /**
    * @runInSeparateProcess
    * @preserveGlobalState disabled
    */
    public function testDriveFail()
    {
    $mock = Mockery::mock(‘overload:\MongoDB\Driver\Manager’);

Leave a Reply

Your email address will not be published. Required fields are marked *