Doctrine orm 原则不';由PhpUnit很好地找到
我对phpunit是个新手 我用这个片段来嘲笑我的EntityManagerDoctrine orm 原则不';由PhpUnit很好地找到,doctrine-orm,phpunit,Doctrine Orm,Phpunit,我对phpunit是个新手 我用这个片段来嘲笑我的EntityManager $emMock = $this->getMock('\Doctrine\ORM\EntityManager', array('getRepository', 'getClassMetadata', 'persist', 'flush'), array(), '', false); $emMock->expects($this->any()) -&
$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));
当我运行我的测试时,我有这个错误
错误:调用未定义的方法it\foo\Entity\File::findBy()
如何模拟此方法?如果查看代码,您将看到其中至少有一行调用了
getRepository()
,并使用结果对其应用函数findBy()
。这是Doctrine2程序的标准行为
您只模拟了EntityManager
——您在变量$emMock
中有模拟。其中一个(模拟)函数,getRepository()
返回一个类为\it\foo\Entity\File
的对象,该对象是在第5行中创建的
我假设类\it\foo\Entity\File
没有实现与Doctrine2存储库相同的接口,至少它显然没有实现findBy()
,因此会出现错误消息
要解决此问题,您需要将getRepository
的mock函数的返回值替换为e real Repository(这通常不是您在单元测试中想要的)或另一个mock:
$repoMock = $this->getMock('Doctrine\ORM\EntityRepository', [], [], '', false);
$emMock->expects($this->any())
->method('getRepository')
->will($this->returnValue($repoMock);
很可能您还必须模拟存储库中的一些函数,例如
findBy()
,它可能会返回您希望测试使用的条目列表。这个答案是否有帮助,或者缺少什么?