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.

class Foo
{
    public function bar() {
        Utils::staticFunction();
        // do another thing
    }
}

And the test class:

use \Mockery as m;
use Foo;

class FooTest
{
    public function testBar() {
        $out = new Foo();
        
        $utils = m::mock('alias:Utils');
        $util->shouldReceive('staticFunction')->withAnyArgs();
        
        $out->bar(); 
        // do another mock and test
    }
}

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:

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

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

 /**
  * @runInSeparateProcess 
  * @preserveGlobalState disabled
  */

  public function testBar() {
        $out = new Foo();
        
        $utils = m::mock('alias:Utils');
        $util->shouldReceive('staticFunction')->withAnyArgs();
        
        $out->bar(); 
        // do another mock and test
    }

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: