Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to configure method "first" which cannot be configured because it does not exist, has not been specified, is final, or is static

I'll try to create a mock objet to test my application and i've got an error thant i can't fix :

    $userOwnLevy = $this->createMock(User::class);

    $userHasContract = $this->createMock(UserHasContract::class);
    $userHasContract->method('getUser')->willReturn($userOwnLevy);

    $firstUserHasContract = $this
        ->getMockBuilder(UserHasContract::class)
        ->getMock()
        ->method('first')
        ->willReturn($userHasContract);

    $contract = $this->createMock(Contract::class);
    $contract->method('getUserHasContract')->willReturnMap([$firstUserHasContract]);

    $levy = $this->createMock(Levy::class);
    $levy->method('getContract')->willReturn($contract);

The goal is to mock this object :

$levy->getContract()->getUserHasContract()->first()->getUser();

I try this :

        $firstUserHasContract = $this
        ->getMockBuilder(UserHasContract::class)
        ->setMethods(['first'])
        ->getMock()
        ->method('first')
        ->willReturn($userHasContract);

But i got this error

Call to a member function first() on null

So if everyone could help me to understand ? Thanks by advance

like image 572
psylo66 Avatar asked Dec 07 '25 02:12

psylo66


2 Answers

Please change willReturnMap to willReturn:

$contract->method('getUserHasContract')->willReturn([$firstUserHasContract]);
like image 179
Kamil Adryjanek Avatar answered Dec 09 '25 00:12

Kamil Adryjanek


Let's declare our mock by chronological order

$userOwnLevy = $this->createMock(User::class);
$contract = $this->createMock(Contract::class);
$userHasContractCollection = $this->getMockBuilder(ArrayCollection::class);
$firstUserHasContract = $this->createMock(UserHasContract::class);
$userHasContract = $this->getMockBuilder(UserHasContract::class);

Then declare the methods by the opposite order of $levy->getContract()->getUserHasContract()->first()->getUser();

$firstUserHasContract->method('getUser')->willReturn($userHasContract);
$userHasContractCollection->method('first')->willReturn($firstUserHasContract);
$contract->method('getUserHasContract')->willReturn($userHasContractCollection);
$userOwnLevy->method('getContract')->willReturn($contract);
like image 35
goto Avatar answered Dec 08 '25 23:12

goto