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
Please change willReturnMap to willReturn:
$contract->method('getUserHasContract')->willReturn([$firstUserHasContract]);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With