嘲笑失败,“无法加载模拟...类在以 --代码覆盖率运行时已存在'

我试图嘲笑phpunit的类。Php 单元失败,出现错误 。这是我运行的唯一测试,因此不能是该类已被模拟的情况。Could not load mock ... class already exists

任何建议将不胜感激。

以下是错误情况:

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());
    }
}

在没有工作的情况下运行它时:--code-coverage

[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)

但是,当它一起运行时,它会失败:--code-coverage

[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

您应该在模拟此类的函数之前添加这些批注。

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

作为参考,您可以查看 phpunit 文档。

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

我遇到了同样的问题,并像这样修复:

  1. 在我的单元测试中还有另一个测试(不是嘲笑测试),它在PHP文件上有我正在模拟的类。我已经删除了那行。require_once
  2. 我已添加到测试套件中processIsolation="true"

推荐