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
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
I ran into the same issue and fixed like this:
require_once
on the PHP file that had the class I was mocking. I've removed that line.processIsolation="true"
in test suiteIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With