Hett
Hett

Reputation: 3825

Is it possible to return mock from mocked method?

I have the Factory

class DocumentManagerFactory
{
    ....   
    public function createDocumentManager(): DocumentManager
    {
        return DocumentManager::create($this->client, $this->configuration);
    }
}

And I want to mock the DocumentManager which returns by createDocumentManager

    $dmStub = $this->createMock(DocumentManager::class)
        ->method('refresh')
        ->willReturnArgument(1);

    $dmFactoryStub = $this->createMock(DocumentManagerFactory::class)
        ->method('createDocumentManager')
        ->willReturn($dm);

I get the following Error:

Method createDocumentManager may not return value of type PHPUnit\Framework\MockObject\Builder\InvocationMocker, its return declaration is ": Doctrine\ODM\MongoDB\DocumentManager"

Is it possible?

Upvotes: 5

Views: 1633

Answers (1)

Dirk Scholten
Dirk Scholten

Reputation: 1048

It's because you are chaining your invocations to the mock and then assigning those to the variable. If you split them up it should work without issue.

$dmStub = $this->createMock(DocumentManager::class);
$dmStub->method('refresh')
       ->willReturnArgument(1);

$dmFactoryStub = $this->createMock(DocumentManagerFactory::class);
$dmFactoryStub->method('createDocumentManager')
              ->willReturn($dm);

In this situation the variable actually holds the object instead of the invocation.

Upvotes: 7

Related Questions