PHPUnit和Doctine:如何模拟我的实体?

时间:2019-12-01 17:05:37

标签: php symfony phpunit symfony-3.4

我正在用Symfony3.4创建一个库。而且我正在用PHPUnit进行测试。

我有一个从数据库中检索数据的方法,我有两个有关联的实体Collection()和CollectionElement():

public function recording()
    {
        try {
            // [...]

            $collection = new Collection();
            $collection->setNomCollection($dbname);

            $collectionExists = $this->em->getRepository(Collection::class)
                ->findOneBy(['nomCollection' => $dbname]);

            // if user provided specific values for $file1, $file2, ... parameters.
            if ((empty($collectionExists)) and (count($datafile) > 0)) {
                // For now, assume USING/OPENING a database is to be done in READ ONLY MODE.
                $this->em->persist($collection);
                $this->em->flush();
            } else {
                $collection = $collectionExists;
            }

            // [....]

            $this->seqcount = count($temp_r);

            foreach($temp_r as $seqid => $line_r) {
                // Check if the file already exists
                $collectionElementExists = $this->em->getRepository(CollectionElement::class)
                    ->findOneBy(['fileName' => $line_r["filename"]]);

                if(empty($collectionElementExists)) {
                    $collectionElement = new CollectionElement();
                    $collectionElement->setIdElement($line_r["id_element"]);
                    $collectionElement->setCollection($collection);
                    $collectionElement->setFileName($line_r["filename"]);
                    $collectionElement->setSeqCount(count($temp_r));
                    $collectionElement->setLineNo($line_r["line_no"]);
                    $collectionElement->setDbFormat($line_r["dbformat"]);

                    $this->em->persist($collectionElement);
                    $this->em->flush();
                }
            }
        } catch (\Exception $e) {
            throw new \Exception($e);
        }
    }

然后我必须进行一些测试,但无法管理EntityManager的模拟:

    $collection = new Collection();
    $collection->setId(3);
    $collection->setNomCollection("db1");     
    $mockedEm = $this->createMock(EntityManager::class);

 $this->collectionMock = $this->getMockBuilder('AppBundle\Entity\IO\Collection')
            ->setMethods(['findOneBy'])
            ->getMock();
 $this->collectionMock->method("findOneBy")->will($this->returnValue($collection));

请问我该怎么做才能完成这项工作?此外,两个实体都调用findOneBy()...

谢谢:)

1 个答案:

答案 0 :(得分:2)

您正确地以此嘲弄了经理。

$mockedEm = $this->createMock(EntityManager::class);

您错过的是对getRepository的调用。

$repo = $this->createMock(EntityRepository::class);
$mockedEm->expects($this->once())->method('getRepository')->with(CollectionElement::class)->willReturn($repo);

之后,您可以对存储库中的findOneBy有所期待。

$repo->expects($this->exactly(2))->method('findOneBy')
  ->withConsecutive(['fileName' => 'f1'], ['fileName' => 'f2'])
  ->willReturnOnConsecutiveCalls($entity1, $entity2);