如何使用 PhpUnit 仅模拟 Laravel 的一种方法

How to mock only one method with Laravel using PhpUnit

我有这个测试:

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Services\AccessTokenService;
use App\Services\MemberService;

class BranchTest extends TestCase    

public function testPostBranchWithoutErrors()
    {
        $this->mock(AccessTokenService::class, function ($mock) {
            $mock->shouldReceive('introspectToken')->andReturn('introspection OK');
        });

        $this->mock(MemberService::class, function ($mock) {
            $mock->shouldReceive('getMemberRolesFromLdap')->andReturn(self::MOCKED_ROLES);
        });

如您所见,此测试有 2 个模拟。第二个 'MemberService:class' 是我目前的问题。在这个 class 中有 2 个函数:'createMember' 和 'getMemberRolesFromLdap'。我明确表示我只想模拟 'getMemberRolesFromLdap' 函数。

在文档中,它是这样写的:

You may use the partialMock method when you only need to mock a few methods of an object. The methods that are not mocked will be executed normally when called:

$this->partialMock(Service::class, function ($mock) { $mock->shouldReceive('process')->once(); });

但是当我使用"partialMock"时,我有这个错误:

Error: Call to undefined method Tests\Feature\BranchTest::partialMock()

当我尝试 classic 模拟(无部分)时,出现此错误:

Received Mockery_1_App_Services_MemberService::createMember(), but no expectations were specified

当然是因为这个 class 中有 2 个函数,所以 PhpUnit 不知道如何处理函数 'createMember'。

接下来我可以尝试什么?我是 PhpUnit 测试的初学者。

编辑

Laravel 6.0
PhpUnit 7.5

PartialMock shorthand 首次添加在 Laravel 6.2 见 release notes。所以升级到 6.2 应该可以解决您的问题。

其次,您可以将以下代码段添加到您的 Tests\TestCase.php class 中,它应该可以工作。

protected function partialMock($abstract, Closure $mock = null)
{
    return $this->instance($abstract, Mockery::mock(...array_filter(func_get_args()))->makePartial());
}