学说不好 findBy PhpUnit

Doctrine don't fine findBy PhpUnit

我是 phpunit 的新手。

我使用这个片段来模拟我的 EntityManager

$emMock = $this->getMock('\Doctrine\ORM\EntityManager',
            array('getRepository', 'getClassMetadata', 'persist', 'flush'), array(), '', false);
    $emMock->expects($this->any())
            ->method('getRepository')
            ->will($this->returnValue(new \it\foo\Entity\File()));
    $emMock->expects($this->any())
            ->method('persist')
            ->will($this->returnValue(null));
    $emMock->expects($this->any())
            ->method('getClassMetadata')
            ->will($this->returnValue((object) array('name' => 'aClass')));
    $emMock->expects($this->any())
            ->method('flush')
            ->will($this->returnValue(null));

当我 运行 我的测试出现这个错误

Error: Call to undefined method it\foo\Entity\File::findBy()

如何模拟此方法?

如果您查看您的代码,您会发现其中至少有一行调用 getRepository() 并使用结果在其上应用函数 findBy()。这是 Doctrine2 程序的一个非常标准的行为。

您仅在模拟 EntityManager - 您在变量 $emMock 中拥有模拟。 (模拟)函数之一,getRepository() return 是您在第 5 行创建的 class \it\foo\Entity\File 的对象。

我想 class \it\foo\Entity\File 没有实现与 Doctrine2 存储库相同的接口,至少它显然没有实现 findBy(),所以出现错误消息。

要解决此问题,您需要将 getRepository 的模拟函数的 return 值替换为真实的存储库(这通常不是您在单元测试中想要的)或另一个模拟:

$repoMock = $this->getMock('Doctrine\ORM\EntityRepository', [], [], '', false);
$emMock->expects($this->any())
        ->method('getRepository')
        ->will($this->returnValue($repoMock);

您很可能还必须模拟存储库中的某些函数,例如 findBy() 可能 return 您希望测试使用的条目列表。