尝试配置无法配置的方法“first”,因为它不存在,尚未指定,是最终的,或者是静态的

时间:2018-02-02 08:37:02

标签: symfony mocking phpunit

我会尝试创建一个模拟对象来测试我的应用程序,我有一个错误,我无法修复:

    $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);

目标是模仿这个对象:

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

我试试这个:

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

但我收到了这个错误

Call to a member function first() on null

所以,如果每个人都能帮助我理解? 谢谢提前

3 个答案:

答案 0 :(得分:1)

让我们按时间顺序宣布我们的模拟

$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);

然后按照$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);

答案 1 :(得分:1)

请将willReturnMap更改为willReturn

$contract->method('getUserHasContract')->willReturn([$firstUserHasContract]);

答案 2 :(得分:0)

谢谢你们我已经合并了你们的答案并且它有效,这是结果:

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

    $firstUserHasContract->method('getUser')->willReturn($userOwnLevy);
    $userHasContractCollection->method('first')->willReturn($firstUserHasContract);
    $contract->method('getUserHasContract')->willReturn($userHasContractCollection);
    $levy->method('getContract')->willReturn($contract);