【问题标题】:Doctrine don't fine findBy PhpUnitDoctrine don't fine findBy PhpUnit
【发布时间】:2016-11-14 22:02:33
【问题描述】:

我是 phpunit 的新手。

我使用这个 sn-p 来模拟我的 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));

运行测试时出现此错误

错误:调用未定义的方法 it\foo\Entity\File::findBy()

如何模拟这个方法?

【问题讨论】:

    标签: doctrine-orm phpunit


    【解决方案1】:

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

    您只模拟了EntityManager - 您在变量$emMock 中有模拟。其中一个(模拟的)函数,getRepository() 返回一个类 \it\foo\Entity\File 的对象,您在第 5 行创建它。

    我猜想\it\foo\Entity\File这个类没有实现与Doctrine2仓库相同的接口,至少它显然没有实现findBy(),所以出现了错误信息。

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

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

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

    【讨论】:

    • 这个答案有帮助还是缺少什​​么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 2018-08-21
    • 2012-08-03
    • 1970-01-01
    相关资源
    最近更新 更多