【问题标题】:How to test Doctrine Entity Manager findOneById method with prophecy?如何用预言测试 Doctrine Entity Manager findOneById 方法?
【发布时间】:2015-03-20 00:28:04
【问题描述】:

我正在使用预言来编写我的单元测试

"require": {
    ...,
    "phpspec/prophecy-phpunit": "~1.0"
},

我有一个电话给

 $dbUser = $this
            ->em
            ->getRepository('MainBundle:User')
            ->findOneById($id);

在测试这个时我得到一个错误,因为方法 findOneByProperty 没有定义。除了把原来的代码改成:

 $dbUser = $this
            ->em
            ->getRepository('MainBundle:User')
            ->findOneBy(array('id' => $id);

我没有找到任何其他解决方法。 有什么方法可以使用预言来测试它并保留原始代码?

【问题讨论】:

  • 看来你必须使用MagicCallPatch 但我不知道这些是如何应用的(从未使用过预言,但很想了解如何模拟魔术方法),我找不到任何文件
  • 这需要预言吗?
  • 这个问题和最后一个问题似乎需要更多的眼睛。你想要其中一个赏金吗?如果有,哪个最需要看?

标签: php symfony doctrine-orm phpunit


【解决方案1】:

如果“原始代码”是指客户端代码,则可以通过创建自定义实体存储库来解决此问题。

class UserRepository extends EntityRepository
{
    public function findOneById(int $id)
    {
        return parent::findOneById($id);
    }
}

供参考http://symfony.com/doc/current/doctrine/repository.html

在你的测试中

$userRepository = $this->prophesize(UserRepository::class);

$em = $this->prophesize(EntityManagerInterface::class);
$em->getRepository('MainBundle:User')->willReturn($userRepository->reveal());

【讨论】:

    【解决方案2】:

    当您通过主键搜索时,您可以简单地使用 find()。所以,你的代码可以这么简单:

    $dbUser = $this
               ->em
               ->getRepository('MainBundle:User')
               ->find($id);
    

    See here 了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-10
      • 1970-01-01
      • 2015-01-25
      • 1970-01-01
      • 2014-09-30
      • 2013-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多