Mockery fails with 'Could not load mock … class already exists' when running with --code-coverage

帅比萌擦擦* 提交于 2020-07-20 07:10:20

问题


I am trying to mock a class for phpunit. Php unit fails with the error Could not load mock ... class already exists. This is the only test I'm running, so it can't be the case that the class is mocked already.

Any suggestion would be appreciated.

Here is the error case:

namespace Tests\Feature;

use Tests\TestCase;

class DeactivateACSTest extends TestCase
{
    public function testDeactivateAcs()
    {
        $deviceController = \Mockery::mock('overload:App\Http\Controllers\Cloud\DeviceController');
        $deviceController
            ->shouldReceive('deactivateACS')
            ->andReturn('hilfehilfehilfe');

        $devCon = new \App\Http\Controllers\Cloud\DeviceController();
        $this->assertEquals('hilfehilfehilfe', $devCon->deactivateACS());
    }
}

When running it without --code-coverage it works:

[13:10:15] vagrant@homestead [~/Code/ekp] $ phpunit --filter DeactivateACS
PHPUnit 6.5.10 by Sebastian Bergmann and contributors.


 ==> Tests\Feature\DeactivateACSTest              ✓

Time: 1.08 seconds, Memory: 16.00MB

OK (1 test, 3 assertions)

However, when running it with --code-coverage it fails:

[13:10:23] vagrant@homestead [~/Code/ekp] $ phpunit --coverage-html coverage --coverage-text=code_coverage.txt --filter DeactivateACSTest
PHPUnit 6.5.10 by Sebastian Bergmann and contributors.


  ==> Tests\Feature\DeactivateACSTest              ⚈

Time: 5.79 seconds, Memory: 44.00MB

There was 1 error:

1) Tests\Feature\DeactivateACSTest::testDeactivateAcs
Mockery\Exception\RuntimeException: Could not load mock \App\Http\Controllers\Cloud\DeviceController, class already exists

/home/vagrant/Code/ekp/vendor/mockery/mockery/library/Mockery/Container.php:220
/home/vagrant/Code/ekp/vendor/mockery/mockery/library/Mockery.php:116
/home/vagrant/Code/ekp/tests/Feature/DeactivateACSTest.php:11

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

Generating code coverage report in HTML format ... done

回答1:


You should add these annotations before the functions that are mocking this class.

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

For reference you can check out the phpunit documentation.

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

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




回答2:


I ran into same issue and fixed like this:
1. There was another test in my unit tests (not mockery test) which had require_once on the php file that had the class I was mocking. Removed that line.
2. Added processIsolation="true" in testsuite



来源:https://stackoverflow.com/questions/51708289/mockery-fails-with-could-not-load-mock-class-already-exists-when-running-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!