php - 使用 --code-coverage 运行时,Mockery 失败并显示 'Could not load mock ... class already exists'

标签 php unit-testing phpunit code-coverage php-7.0

我正在尝试为 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

最佳答案

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

/**
 * @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

关于php - 使用 --code-coverage 运行时,Mockery 失败并显示 'Could not load mock ... class already exists',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51708289/

相关文章:

c++ - 测试目录中的另一个 main.cpp

使用 MVC 框架的 PHP 数据库在运行 PHPUnit 测试后收到错误消息

php - 使用 Mockery 模拟在另一个静态方法中调用的静态方法

php - 根据复选框编辑中间表

php - 使用 PHP 比较递增的系列值

php - 在 Laravel 中为 Controller 传递默认数据

php - 每次服务器表加载传输的数据时,如何向收件人发送包含表数据的电子邮件?

android - 我如何在android中为挂起功能和状态流编写单元测试

unit-testing - 软件测试 : test remote API or just use a mock?

PHPunit 在进度条点中有空格