PHPUnit Symfony:如何使用多个参数模拟相同的方法?

PHPUnit Symfony : how do I mock same method with multiple arguments?

你好尝试测试我的控制器这个控制器调用 getRepository 方法 getRepopsitory 是 DocumentManager 的一个函数。

我必须将不同的参数传递给 getREpository(),但是当我尝试模拟 DocumentManager 并设置方法 getRepository 时,我无法模拟具有两个不同结果的方法。

我的测试:

<?php

  public function testGetLetter()
    {
        $_box = new Box();
        $_box->setName('test-A');
        $_box->setId('abc01');
        $_boxId = $_box->getId();
        $ids = [];

        for ($i = 0; $i < 10; $i++) {
            $letter = new letter();
            $letter->setContent('content: ' . $i);
            $_box->addLetter($letter);
            $letter->setBox($_box);
            $ids[] = $_boxId;
        }

        $request = $this->createMock("Symfony\Component\HttpFoundation\Request");

        $boxRepository = $this->createMock(BoxRepository::class);
        $boxRepository->expects($this->once())
            ->method('find')
            ->willReturn($_box);

        $letterRepo = $this->createMock(LetterRepository::class);


        $documentManager = $this->getMockBuilder(DocumentManager::class)
            ->disableOriginalConstructor()
            ->setMethods(['getRepository'])
            ->getMock();

        $documentManager->expects($this->once())
            ->method('getRepository')
            ->with($this->equalTo('Bundle:Box'))
            ->will($this->returnValue($boxRepository));


        $documentManager->expects($this->once())
            ->method('getRepository')
            ->with($this->equalTo('Bundle:Letter'))
            ->will($this->returnValue($letterRepo));


        $boxControler = new boxController();


        $boxControler->getletters($palletId, $documentManager, $request);

    }

我的控制器

public function getletters(string $id, DocumentManager $dm, Request $request): Response
    {
        $box = $dm->getRepository('Bundle:Box')->find($id);

        $letters = $box->getLetters();
        $letterRepository = $dm->getRepository('Bundle:Letter');
        $result = [];
        foreach ($letters as $letter){
            $result [] = $letterRepository->prepareLetterData($letter);
        }
        return $this->setResponse($result, $request);
    }

错误:

Testing Tests\Controller\BoxControllerTest

Expectation failed for method name is equal to "getRepository" when invoked 1 time(s)
Parameter 0 for invocation DocumentManagerDecorator::getRepository('Bundle:Box') does not match expected value.
Failed asserting that two strings are equal.
Expected :'Bundle:Letter'
Actual   :'Bundle:Box'
 <Click to see difference>

 /var/www/html/Controller/BoxController.php:151
 /var/www/html/Tests/Controller/BoxControllerTest.php:147

我看到了 this post 但我无法将回复应用到我的情况中

您可以使用 at()

$mock->expects($this->at(0))
    ->method('foo')
    ->willReturn('firstValue');

$mock->expects($this->at(1))
    ->method('foo')
    ->willReturn('secondValue');

或如@iainn 所述returnValueMap FROM PHPUnit doc